我正在尝试使用 angular2 基于参数进行 api 调用。我需要在组件初始化和参数更改时进行此 api 调用。下面是我正在使用的代码。问题是,当 ngOnInit 运行时,它会使用参数调用 api,然后立即订阅更改,从而再调用 api 2 次。
处理这种情况的正确方法是什么,以便 api 调用仅在 init 时调用一次,同时仍然能够观察参数的更改?
ngOnInit() {
Observable.zip(this.route.queryParams, this.route.params).subscribe((params: any) => {
this.queryParams = params[0];
this.params = params[1];
this.get();
this.subscribe();
});
}
subscribe() {
this.queryParamsSub = this.route.queryParams.subscribe((params: any) => {
this.queryParams = params;
this.get();
});
this.paramsSub = this.route.params.subscribe((params: any) => {
this.params = params;
this.get();
});
}
// this is called 3 times on init
get() {
this.apiManager.get(this.queryParams, this.params);
}
ngOnDestroy() {
this.queryParamsSub.unsubscribe();
this.paramsSub.unsubscribe();
}
最佳答案
ngOnInit
还不够吗(无需调用 subscribe
)?您已通过 zip
订阅了更改。为什么要再次重新订阅?或者我错过了一些明显的事情?
ngOnInit() {
Observable.zip(this.route.queryParams, this.route.params).subscribe((params: any) => {
this.queryParams = params[0];
this.params = params[1];
this.get();
});
}
关于javascript - init 上的 api 调用和参数更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443374/