可以在组件的构造函数中注入 ActivatedRoute 和 Router,然后在订阅 HTTP 请求时,使用 Router 对象来导航到所需的页面。
示例代码:
import { Component } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { HttpClient } from '@angular/common/http';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent { constructor(private http: HttpClient, private route: ActivatedRoute, private router: Router) {}
onSubmit() { this.http.post('/api/my-resource', {}).subscribe( () => { // If the response is a 204 status code, navigate to a different page this.router.navigate(['/different-page'], { relativeTo: this.route }); }, error => console.error(error) ); } }
在上面的代码中,我们在组件的构造函数中注入了 ActivatedRoute 和 Router 对象。在 onSubmit 方法中,我们订阅了一个 HTTP POST 请求,并在响应返回时检查状态码是否为 204。如果是 204,就使用 Router 对象导航到所需的页面。 在调用 navigate 方法时,我们使用了 '/' 前缀来指定绝对路径,然后使用 relativeTo 选项来创建相对路径。这样,如果我们要为相对于当前组件的路由定义路由,就可以不必硬编码它们的路径。