【问题标题】:call api serially in angular with rxjs使用 rxjs 以角度连续调用 api
【发布时间】:2019-02-21 13:01:11
【问题描述】:

假设我有 3 个在 app.component 中调用的服务,每个服务 subscribe() 在自己的服务中,那么我怎样才能得到一个一个响应。

app.component.ts

ngOnInit() {
  this._salesstageService.refreshSalesstage();
  this._opportunityMailsService.RefreshTop50();
  this._opportunityService.getOpportunities();
}

例如,我有三个 service.ts 文件,但在这里您可以看到一个调用 api 的服务函数。

app.service.ts

   getOpportunities() {
       return this.http.get(this._opportunitiesUrl)
        .do(res => this._errorService.checkResponse(res))
        .map(res => <Opportunity[]>JSON.parse(res.text(), 
              this.opportunityReviver))
        .catch(err => this._errorService.handleError<Opportunity[]>(err))
        .subscribe(
          opportunities => {
            if(opportunities instanceof Array){
                this._opportunities = opportunities;
               this.opportunities$.next(this._opportunities);
            }
        })
    } 

【问题讨论】:

  • 添加这些服务的签名,最好是它们的实现

标签: angular rxjs angular-services


【解决方案1】:

由于您的服务似乎发布了 observable,因此以嵌套方式订阅它们。

this._salesstageService.salesstage$.subscribe(() => {
  this._opportunityMailsService.RefreshTop50();
  this._opportunityMailsService.mail$.subscribe(() => this._opportunityService.getOpportunities());
});

this._salesstageService.refreshSalesstage();

【讨论】:

  • 我认为,它不会起作用,因为每当api更新时订阅都会调用,但是这3个api服务会在app.component中一次调用一次,它应该串行调用。
  • 链接它们将连续调用它们。您在其他订阅方法中订阅。
猜你喜欢
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 2020-01-29
  • 2016-06-05
  • 1970-01-01
相关资源
最近更新 更多