有观察者:
export class ListenerService {
private action: Subject<IActionData> = new Subject();
apply(data?: IActionData) {
this.action.next(data);
}
changes(): Observable<any> {
return this.action.asObservable();
}
}
使用方式是
this.sub = this.listener.changes();
this.sub.subscribe((res: IActionData) => {});
在销毁组件中,我试图取消设置this.sub
:
ngOnDestroy() {
if (this.sub) {
console.log(this.sub);
this.sub.unsubsribe();
}
}
它说:
错误TypeError:this.sub.unsubsribe不是函数 在VersionsAddressComponent.ngOnDestroy
答案 0 :(得分:2)
订阅值
sub: Subscription;
您的订阅将是
this.sub = this.listner.changes.subscribe((res: IActionData) => {});
然后onDestroy将
ngOnDestroy() {
this.sub.unsubsribe();
}
答案 1 :(得分:1)
那应该做的:
this.sub = this.listener.changes().subscribe((res: IActionData) => {});
this.sub.unsubsribe();
答案 2 :(得分:1)
您必须使用RXJS订阅:
subscription = new Subscription() ;
this.subscription.add(this.listener.changes().subscribe((res: IActionData) => {}));
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
答案 3 :(得分:0)
Observable
不能退订,subscription
可以退订:
例如:
this.sub = this.listener.changes().subscribe((res: IActionData) => {});
然后您可以按照完成的方式取消订阅:
ngOnDestroy() {
this.sub.unsubsribe();
}