The*_*ult 18 observable rxjs typescript rxjs6
我刚刚观看了 John Papa 的 ngConf 视频,将 SubSink 作为取消订阅可观察对象的最佳实践。
我实际上是在使用 Subscriptions[] 然后将订阅推送到其中然后 forEach 在 cmp destroy 取消订阅。
我错过了他们的东西还是只是使用 SubSink 的可读性改进?
Sho*_*ogg 21
另一种不安装第三方库的方法是使用 .add() 方法将订阅分组
export class CustomerComponent implements OnInit, OnDestroy {
constructor(
private dataService: DataService
){}
private subs = new Subscription();
ngOnInit() {
this.subs.add(this.dataService.getCustomer().subscribe());
this.subs.add(this.dataService.getProducts().subscribe());
}
ngOnDestroy() {
this.subs.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
Jul*_*ius 12
采用这种方式至少有一个好处 - 您可以将此代码移到应用程序逻辑之外。因为退订只是清理(必须)。它与您在应用程序中创建的逻辑无关。
更进一步,您可以省略ngOnDestroy组件并创建一个带有已NgOnDestroy实现的适配器并将所有逻辑放置在那里。
import { OnDestroy } from '@angular/core';
import { SubSink } from './sub-sink';
/**
* A class that automatically unsubscribes all observables when
* the object gets destroyed
*/
export class UnsubscribeOnDestroyAdapter implements OnDestroy {
/**The subscription sink object that stores all subscriptions */
subs = new SubSink();
/**
* The lifecycle hook that unsubscribes all subscriptions
* when the component / object gets destroyed
*/
ngOnDestroy(): void {
this.subs.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
除此之外,它是一个非常小的包,只有几行代码。感谢分享 :)
| 归档时间: |
|
| 查看次数: |
7772 次 |
| 最近记录: |