我在一个页面中使用material表,我希望它的表数据源每5秒刷新一次,这样值中的任何更改都将反映在表中。这就是我现在所做的:
everyFiveSeconds: Observable<number> = timer(0, 5000);
ngOnInit() {
this.everyFiveSeconds.subscribe(() => {
this.getComponents();
});
getComponents()
发送get请求并将输出分页到材料表。然而,问题是,一旦我最初加载了这个页面,get请求就会每5秒发出一次。但是,即使我导航到另一个页面,应用程序也会继续发送请求。如果我重新访问页面,请求每2.5秒发送一次,如果我重复请求,请求的频率就会不断增加。
如何修改我的代码,以便仅当我坐在此组件页面时发送此get请求,并确保如果我重新访问此页面,则不会创建多个计时器?
发布于 2020-05-07 01:02:21
大概是这样的:
import { timer } from 'rxjs';
export class MyClass implements OnInit, OnDestroy {
subscription: Subscription;
everyFiveSeconds: Observable<number> = timer(0, 5000);
ngOnInit() {
this.subscription = this.everyFiveSeconds.subscribe(() => {
this.getComponents();
});
}
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
发布于 2020-05-07 01:09:12
建议您取消订阅所有具有不确定排放数量的可观测数据。永远不要认为框架会帮你做到这一点。您可以使用取消订阅来做到这一点,但就我个人而言,我更喜欢使用带有takeUntil
运算符的Subject
。如果您有几个要取消订阅的可观察对象,这种方法特别有用(尽管我喜欢在代码中保留一个模式,所以即使只有一个订阅要处理,我也会使用它):
private _destroy$ = new Subject<void>();
ngOnInit() {
this.everyFiveSeconds
// You can do this with all of your subscriptions
// using a single _destroy$ variable
.pipe(takeUntil(this._destroy$))
.subscribe(() => {
this.getComponents();
});
}
ngOnDestroy() {
if(this._destroy$ && !this._destroy$.closed) {
this._destroy$.next();
this._destroy$.complete();
}
}
https://stackoverflow.com/questions/61640548
复制相似问题