如何在Angular 2+中执行多个http请求,但等待每个请求完成后再执行下一个?

时间:2019-02-12 09:13:07

标签: angular rxjs

我有类似的东西:

// 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运算符。

2 个答案:

答案 0 :(得分:4)

只需使用concat。上一个Observable完成后,它将一个接一个地订阅每个源Observable。

import { concat } from 'rxjs';

...

concat(...requests).pipe(
  toArray(), // Collect all responses to a single array
).subscribe((results) => ...);

也许您甚至都不使用toArray,这取决于您要对响应执行什么操作。

答案 1 :(得分: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 }];
        }
      });
  }