Mig*_*ias 3 typescript angular
我BehaviorSubject在我的一个服务中创建,并使用它asObservable稍后订阅它,但我需要在控制器被销毁后取消订阅,我该如何取消订阅它.
服务
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);
}
Run Code Online (Sandbox Code Playgroud)
调节器
import { ReaderService } from '../../../../services/reader/reader.service';
constructor(
private readerServices: ReaderService
) { }
ngOnInit() {
this.initDocumentData();
this.readerServices.currentStepObservable
.subscribe((step) => {
this.currentStep = step;
});
}
ngOnDestroy() {
}
Run Code Online (Sandbox Code Playgroud)
尝试带有帮助的内在主题的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();
}
}
Run Code Online (Sandbox Code Playgroud)
将其分配给一个subscription类型的变量Subscription,可import从编rxjs,然后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();
}
Run Code Online (Sandbox Code Playgroud)
async在模板中使用管道:import { ReaderService } from '../../../../services/reader/reader.service';
currentStep$;
constructor(
private readerServices: ReaderService
) {}
ngOnInit() {
this.initDocumentData();
this.currentStep$ = this.readerServices.currentStepObservable;
}
Run Code Online (Sandbox Code Playgroud)
然后在模板中:
{{ this.currentStep$ | async }}
Run Code Online (Sandbox Code Playgroud)
这样,您就不必unsubscribe处理来自 的 ing,Observable而 Angular 会处理它。
| 归档时间: |
|
| 查看次数: |
2146 次 |
| 最近记录: |