source

Angular - 여러 HTTP 호출을 순차적으로 수행합니다.

ittop 2023. 6. 26. 23:09
반응형

Angular - 여러 HTTP 호출을 순차적으로 수행합니다.

첫 번째 통화에서 사용자의 IP 주소를 얻고 두 번째 통화에서 해당 IP를 사용하여 사용자를 등록하는 것처럼 한 통화의 응답을 다른 통화로 사용하기 위해 HTTP 통화를 순차적으로 수행하는 기능을 만들어야 합니다.

데모 코드:

registerUser(user: User) {
    this.utility.getIpAddress()
    .subscribe(data => {
        this.ipAddress = data.ip;
    });
    const body = {
        UserName: user.UserName,
        Email: user.Email,
        //...
        UserIP: this.ipAddress,
    }
    return this.http.post(this.registerAPI, body);
}

는 switchMap 연산자를 사용하여 수행할 수 있습니다.이 예제에서는 RxJS 5.5+ 파이프 가능 연산자를 사용합니다.

import { switchMap } from 'rxjs/operators';

registerUser(user: User) {
  return this.utility.getIpAddress().pipe(
    switchMap(data => {
      this.ipAddress = data.ip;

      const body = {
        UserName: user.UserName,
        Email: user.Email,
        UserIP: this.ipAddress,
      };

      return this.http.post(this.registerAPI, body);
    })
  )
}

RxJS < 5.5:

import { switchMap } from 'rxjs/operators';

registerUser(user: User) {
  return this.utility.getIpAddress()
    .switchMap(data => {
      this.ipAddress = data.ip;

      const body = {
        UserName: user.UserName,
        Email: user.Email,
        UserIP: this.ipAddress,
      };

      return this.http.post(this.registerAPI, body);
    });
}

언급URL : https://stackoverflow.com/questions/51212448/angular-make-multiple-http-calls-sequentially

반응형