这通常是由于在订阅时不正确使用流而导致的。为了解决此问题,可以更改订阅的方式并尝试使用ngOnDestroy取消订阅。
例如,使用subscribe()方法将流分配给一个变量,然后在ngOnDestroy中取消订阅:
@Component({...})
export class MyComponent implements OnInit, OnDestroy {
private myObservable$: Observable;
private mySubscription$: Subscription;
constructor(private myService: MyService) {}
ngOnInit() {
this.myObservable$ = this.myService.getData();
this.mySubscription$ = this.myObservable$.subscribe(
data => console.log(data),
error => console.error(error),
() => console.log('Completed')
);
}
ngOnDestroy() {
this.mySubscription$.unsubscribe();
}
}
然而,更好的方法是使用async管道作为模板中的一个简单的变量处理订阅。这样做能使自动取消订阅成为可能,并使订阅的绑定更易于管理。
例如:
@Component({...})
export class MyComponent {
myData$: Observable;
constructor(private myService: MyService) {
this.myData$ = this.myService.getData();
}
}
HTML模板:
{{ myData.name }}
{{ myData.description }}