이전 API가 성공적으로 완료되었을 때 API를 새로 호출하려면 어떻게해야합니까?

Nov 25 2020

저는 angular 및 rxjs를 처음 사용하며 다음 시나리오가 있습니다. api 호출이 성공적으로 해결 된 후 angular / rxjs의 맥락에서 어떻게해야할지 모르겠습니다. 그것

handler(): void {
  this.serviceNAme
    .createDirectory(this.path)
    .pipe(
      finalize(() => {
        this.someProperty = false;
      })
    )
    .subscribe(
      (data) => console.log(data),
      (error) => console.error(error.message)
    );
}

이전 API가 성공했을 때 api를 새로 호출하는 올바른 방법은 무엇입니까?

답변

2 adrisons Nov 26 2020 at 15:07

난 당신이 가지고 이해 serviceOne와를 serviceTwo. serviceTwo에서 검색된 데이터를 사용하여 호출하려고합니다 serviceOne.

rxjs switchMap 을 사용하면 Observable을 다른 것으로 파이프 할 수 있습니다.

    handler(): void {
        this.serviceOne
            .createDirectory(this.path)
            .pipe(
                switchMap(serviceOneResult => {
                    // transform data as you wish
                    return this.serviceTwo.methodCall(serviceOneResult);
                })
            )
            .subscribe({
                next: serviceTwoResult => {
                    // here we have the data returned by serviceTwo
                },
                error: err => {},
            });
    }

당신의 데이터를 전달할 필요가없는 경우 serviceOneserviceTwo그러나 당신이 필요하다고하면 rxjs 사용할 수있는, 모두가 함께 완료 될 forkJoin .

    handler(): void {
        forkJoin([
            this.serviceOne.createDirectory(this.path), 
            this.serviceTwo.methodCall()
        ])
        .subscribe({
            next: ([serviceOneResult, serviceTwoResult]) => {
                // here we have data returned by both services
            },
            error: err => {},
        });
    }
1 DigitalDrifter Nov 26 2020 at 04:21

사용 aysnc하고 await당신이 할 수 있습니다 :

async handler(): void {
  await this.serviceNAme
    .createDirectory(this.path)
    .pipe(
      finalize(() => {
        this.someProperty = false;
      })
    )
    .subscribe(
      (data) => console.log(data),
      (error) => console.error(error.message)
    );

   // Do second api call
}
1 MrkSef Nov 26 2020 at 05:00

이를 수행하는 몇 가지 말이 있습니다.

시나리오 # 1

두 개의 서비스 API 호출은 독립적입니다.

 const serviceCall1 = this.serviceName.createDirectory(this.path);
 const serviceCall2 = this.serviceName.createDirectory(this.otherPath);

 concat(serviceCall1 , serviceCall2).subscribe({
   next: console.log,
   error: err => console.error(err.message),
   complete: () => console.log("service call 1&2 complete")
 });

시나리오 # 2

두 통화는 서로 의존하므로 두 번째 통화를 시작하려면 첫 번째 통화의 결과가 필요합니다.

 this.serviceName.getDirectoryRoot().pipe(
   switchMap(root => this.serviceName.createDirectoryInRoot(root, this.path))
 ).subscribe({
   next: console.log,
   error: err => console.error(err.message),
   complete: () => console.log("service call 1 used to create service call 2, which is complete")
 });

이렇게 하면 첫 번째 호출에서 오류가 발생하면에 결과가 전송 되지 않고 두 번째 호출이 수행되지 않기 때문에 시나리오 # 2switchMap 가 필요합니다.