对init和参数的API调用发生了变化

api call on init and params change

本文关键字:调用 发生了 变化 API init 参数      更新时间:2023-09-26

我正在尝试使用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();
    });
  }