我在我的一项服务中创建了一个BehaviorSubject
,并在以后将其作为可观察的方式使用来进行订阅,但是在控制器被销毁后,我需要取消订阅,我如何才能取消订阅。
服务
import { Observable, BehaviorSubject } from 'rxjs';
private currentStepObject = new BehaviorSubject<number>(0);
public currentStepObservable = this.currentStepObject.asObservable();
constructor(
) { }
public changecurrentStep(step: number): void {
this.currentStepObject.next(step);
}
控制器
import { ReaderService } from '../../../../services/reader/reader.service';
constructor(
private readerServices: ReaderService
) { }
ngOnInit() {
this.initDocumentData();
this.readerServices.currentStepObservable
.subscribe((step) => {
this.currentStep = step;
});
}
ngOnDestroy() {
}
答案 0 :(得分:7)
尝试带有用的内部主题的takeUntil。
更新:在这种情况下,您不必手动取消订阅组件中的每个订阅,因为内部可能不止一个订阅。
import { ReaderService } from '../../../../services/reader/reader.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators'
export class MyComponent implements OnInit, OnDestroy {
private unsubscribe$: Subject<any> = new Subject<any>();
constructor(
private readerServices: ReaderService
) { }
ngOnInit() {
this.initDocumentData();
this.readerServices.currentStepObservable.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe((step) => {
this.currentStep = step;
});
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
答案 1 :(得分:3)
将其分配给类型为subscription
的{{1}}变量,可以从Subscription
import
开始rxjs
,然后在{{1} }
unsubscribe
ngOnDestroy
管道:import { ReaderService } from '../../../../services/reader/reader.service';
import { Subscription } from 'rxjs';
subscription: Subscription;
constructor(
private readerServices: ReaderService
) {}
ngOnInit() {
this.initDocumentData();
this.subscription = this.readerServices.currentStepObservable
.subscribe(step => this.currentStep = step);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
然后在模板中:
async
这样,您就不必照顾import { ReaderService } from '../../../../services/reader/reader.service';
currentStep$;
constructor(
private readerServices: ReaderService
) {}
ngOnInit() {
this.initDocumentData();
this.currentStep$ = this.readerServices.currentStepObservable;
}
中的{{ this.currentStep$ | async }}
了,Angular会照顾好它。
答案 2 :(得分:0)
每个Observable.subscribe()返回一个订阅。最好创建一个预订数组并将所有预订添加到其中。 在销毁组件时(ngOnDestroy生命周期钩子),循环遍历subscriptions数组并对其调用unsubscribe。
这样做,您无需管理来自不同订户的不同订制。
答案 3 :(得分:-1)
您可以这样做
import { ReaderService } from '../../../../services/reader/reader.service';
subscription : Subscription;
constructor(
private readerServices: ReaderService
) { }
ngOnInit() {
this.initDocumentData();
this.subscription = this.readerServices.currentStepObservable
.subscribe((step) => {
this.currentStep = step;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}