每个请求的订阅数量都在增加

时间:2017-07-24 08:50:54

标签: angular rxjs

我是角度和RXJS的新手,所以无法理解为什么返回值的数量在每次请求时都在增加。

服务

subject = new Subject<any>();

get(endpoint: string, params?: URLSearchParams) {
  const headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  headers.append('Authorization', 'Bearer ' + window.localStorage.getItem('accessToken'));

  const opts: any = { headers };
  if (params != null) {
    opts.params = params;
  }
  const options = new RequestOptions(opts);

  let response = this.http.get(this.globals.apiUrl + endpoint, options)
    .map(res => res.json())
    .subscribe((res) => {
      this.subject.next(res);
    });

  return this.subject.asObservable(); 
}

组件:

onGetSmth(){
    this.authService.get('doors').subscribe((doors) => {
      console.log(doors)
    })
}

1 个答案:

答案 0 :(得分:0)

Subjects是多播。当您没有complete主题时,对同一主题的所有订阅都将获得相同的值。因此,每次调用onGetSmth()时,之前的订阅也会获得下一个值。

您可以通过从代码中删除主题并保持简单来解决此问题:

get(endpoint: string, params?: URLSearchParams) {
 const headers = new Headers();
 headers.append('Content-Type', 'application/x-www-form-urlencoded');
 headers.append('Authorization', 'Bearer ' + window.localStorage.getItem('accessToken'));

 const opts: any = {headers: headers};
 if (params != null) {
  opts.params = params;
 }
 const options = new RequestOptions(opts);

 return this.http.get( this.globals.apiUrl + endpoint, options)
  .map(res => res.json());
}

每次调用get().subscribe()时,这都是单播的,因此不会发生值共享。请求完成后,订阅现在也将正确完成。