相关疑难解决方法(0)

Angular2/4:刷新数据实时

我需要在一个间隔中刷新组件页面中的数据.此外,我需要在执行某些操作后刷新数据.我在服务中使用Obeservables,以便我可以在响应准备好时订阅.我正在推送对象的订阅,以便我可以清除它ngDestroy,我认为,我有以下方法来实现相同的目标.

方法1:setInterval

我已经设置了一个间隔ngOnInit,它将以相等的间隔调用refreshData.将使用clearIntervalin ngOnDestroy方法清除interval对象.

export class MyComponent implements OnInit, OnDestroy {
    private subscription: Subscription = new Subscription();

    data: any;
    interval: any;

    ngOnInit() {
        this.refreshData();
        this.interval = setInterval(() => { 
            this.refreshData(); 
        }, 5000);
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
        clearInterval(this.interval);
    }

    refreshData(){
        this.subscription.add(
            this.myService.getData()
                .subscribe(data => {
                    this.data = data;
                })
        );
    }

    doAction(){
        this.subscription.add(
            this.myService.doAction()
                .subscribe(result => {
                    if(result === true){
                        this.refreshData();
                    }
                })
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

Q1:在每次刷新调用时subscription,都会向对象添加一个订阅,这会增加内存使用量,如果用户保持页面打开一段时间,浏览器可能会崩溃吗?

方法2:Observable.timer

此方法使用将在刷新数据后创建的计时器.

export class MyComponent …
Run Code Online (Sandbox Code Playgroud)

memory-leaks subscriptions setinterval angular2-observables angular

16
推荐指数
2
解决办法
4万
查看次数