问题原因:在使用Angular Router的navigate()方法后,HttpClient停止工作并收到400错误请求的原因可能是由于导航触发了未完成的HTTP请求。
解决方法:
import { Component, OnDestroy } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: '...'
})
export class ExampleComponent implements OnDestroy {
private navigationSubscription: Subscription;
constructor(private router: Router, private http: HttpClient) {
// 订阅导航开始事件
this.navigationSubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
// 取消未完成的HTTP请求
this.http.cancel();
}
});
}
ngOnDestroy() {
// 取消订阅导航事件
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}
import { Component, OnDestroy } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-example',
template: '...'
})
export class ExampleComponent implements OnDestroy {
private destroy$: Subject = new Subject();
constructor(private router: Router, private http: HttpClient) {
// 订阅导航开始事件
this.router.events
.pipe(takeUntil(this.destroy$))
.subscribe((event) => {
if (event instanceof NavigationStart) {
// 等待所有HTTP请求完成
this.http.get('/api/data')
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
// 导航之前的逻辑
this.router.navigate(['newRoute']);
});
}
});
}
ngOnDestroy() {
// 销毁Subject
this.destroy$.next();
this.destroy$.complete();
}
}
以上是两种解决方法,你可以根据实际情况选择适合的方法来解决问题。