【问题标题】:How can I perform multiple http request in Angular 2+ but wait for each to complete before doing the next?如何在 Angular 2+ 中执行多个 http 请求,但在执行下一个请求之前等待每个请求完成?
【发布时间】:2019-02-12 17:17:05
【问题描述】:

我有类似的东西:

// Build requests array
const requests = [];
contacts.forEach(contact => {                     
  requests.push(
    this.httpService.post('/users', { name: contact.name })
  );
});

// Run them all at once and do stuff when they all complete
return Observable.forkJoin(requests).pipe(
  map(() => console.log('All requests are done!')),
  catchError(() => console.log('Something went wrong'))
);

像这样使用forkJoin,所有的http请求都是一次性的。我怎样才能一一完成请求?也就是说,我希望请求 1 完成,然后运行请求 2 等。我找不到任何执行此操作的 rxjs 运算符。

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    只需使用concat。当前一个 Observable 完成时,它会一个接一个地订阅每个源 Observable。

    import { concat } from 'rxjs';
    
    ...
    
    concat(...requests).pipe(
      toArray(), // Collect all responses to a single array
    ).subscribe((results) => ...);
    

    也许你甚至不使用toArray,这取决于你想对回复做什么。

    【讨论】:

      【解决方案2】:

      您可以使用flatMap 处理这种类型的http 请求。这是我的一段代码,可以为你工作。

      public sendMailForExit(email) {
          email.employee.token = Common.newGuid();
          return this.http.postRequest(StaticKeywords.url_email + 'InitialSaveEmployeeExitDetails', email).map((response: Response) => {
            return response;
          })
            .flatMap((token: any) => {
              if (token.json().success === true) {
                email.employee.url = StaticKeywords.baseUrlApp + '#/' + StaticKeywords.url_employee + StaticKeywords.url_exitDetail +
                  email.employee.ID + '/' + email.employee.token;
                return this.http.postRequest(StaticKeywords.url_email + 'sendEmail', email).map((innerResponse: Response) => {
                  return this.CheckResponse(innerResponse);
                });
              } else {
                return [{ token: token }];
              }
            });
        }
      

      【讨论】:

      • 我认为这不适用于 OP 要求的 请求数组。
      • 是的,你是对的@HarunYılmaz,我误解了问题
      猜你喜欢
      • 2019-02-11
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多