前の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に新しい呼び出しを行う正しい方法は何ですか?

回答

2 adrisons Nov 26 2020 at 15:07

私はあなたが持っている理解serviceOneしてserviceTwo。そしてserviceTwo、から取得したデータを使用して呼び出しますserviceOne

rxjs switchMapを使用すると、あるオブザーバブルを別のオブザーバブルにパイプできます。

    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

を使用してaysncawait次のことができます。

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

2つのサービス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

2つの呼び出しは相互に依存しているため、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")
 });

このようにすると、最初の呼び出しでエラーが発生すると、結果がに送信されず、2番目の呼び出しが行われないため、シナリオ#2が必要になりますswitchMap