对init和参数的API调用发生了变化
api call on init and params change
我正在尝试使用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();
});
}
事实证明,您可以使用Observable.combineLatest
来组合可观察对象,这将触发每次更改。像这样的代码可以很好地工作:
ngOnInit() {
this.sub = Observable.combineLatest(this.route.queryParams, this.route.params).subscribe((params: any) => {
this.queryParams = params[0];
this.params = params[1];
this.get();
});
}
相关文章:
- IE11中的第二个调用取消了第一个Fetch API调用
- 为什么属性存在于对象实例上,即使其原型发生了更改
- Ajax调用给了我跨域错误
- Javascript函数 - 通过引用复制,但这里发生了什么
- 套接字发生了什么's在'断开连接'事件(服务器端)
- 这段代码中发生了什么
- Wamp没有识别出我的代码发生了更改
- 如何检查输入框值在使用淘汰之前是否发生了更改
- 通过它访问HTML元素's id DIRECTLY-这里发生了什么
- 从根本上说,函数调用出了问题.功能在控制台中确实有效
- window.opener引用在Java 1.7.0_04-b20中从Applet重定向期间发生了更改,但在1.7.0_
- 如何知道JS对象属性的值在哪一行发生了更改
- 查找表单的哪些特定部分在输入时发生了更改
- JavaScript's数组过滤器函数在没有分配函数的情况下使用-这里发生了什么
- 起重行为在铬 48 和 49 之间发生了变化
- 这个JavaScript函数中发生了什么
- 对init和参数的API调用发生了变化
- 当我调用一个函数时真正发生了什么
- 为什么在angular中调用工厂在加载时发生了3次
- 当webservice调用解析JSON对象时,在.net中究竟发生了什么?