gpt4 book ai didi

Angular 订阅/取消订阅最佳实践

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:48 25 4
gpt4 key购买 nike

我目前想知道 Angular 订阅和取消订阅。关于这个主题有很多东西,所以我有点迷失在这一切中。

我应该什么时候退订?如果我从不取消订阅,会发生什么?我从来没有遇到任何来自 reliquat 订阅的错误。

有没有办法自动取消订阅组件/应用程序中的所有内容,这样我就不必通过订阅声明 1 个属性?这可能非常烦人:

@Component({
selector: 'subscriptionTest',
template: `...`,
})
export class SubTestComponent {
first;
second;
third;

constructor(private remote: RemoteService){}

ngOnInit() {
this.first = remote.getSomeData().subscribe(data => // do something);
this.second = Observable.interval(500).subscribe(event => // do something);
this.third = remote.getSomeOtherData().subscribe(data => // do something);

}

ngOnDestroy() {
this.first.unsubscribe();
this.second.unsubscribe();
this.third.unsubscribe();
}

}

最佳答案

如果您不想重复自己,请使用父类(super class):

/**
* Unsubscribe from any Observable using takeUntil and this.destroy$
* someObservable.pipe( // lettable operators in rxjs ^5.5.0
* ...
* takeUntil(destroy$)
* )
* .subscribe(....
**/
export class Destroyer implements OnDestroy {
destroy$: Subject<boolean> = new Subject<boolean>();

ngOnDestroy() {
// Unsubscribe from whatever used takeUntil(destroy$)
this.destroy$.next(true);
// Now let's also unsubscribe from the subject itself:
this.destroy$.unsubscribe();
}
}

到处使用它:

export class SomeComponent extends Destroyer{

constructor(private remote: RemoteService){
super();
}

ngOnInit() {
remote.getSomeData()
.pipe(takeUntil(this.destroy$))
//.takeUntil(this.destroy$) // before rxjs ^5.5.0
.subscribe(data => {/* do something*/});

Observable.interval(500)
.pipe(takeUntil(this.destroy$))
//.takeUntil(this.destroy$) // before rxjs ^5.5.0
.subscribe(data => {/* do something*/});
}
}

// optional. You don't need ngOnDestroy everywhere.
ngOnDestroy(): void {

// Let Destroyer trigger unsubscribe
super.ngOnDestroy();

// ...SomeComponent other cleanup.
}


}

关于Angular 订阅/取消订阅最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47152752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com