简体   繁体   中英

Waiting for API to finish in Angular

In Angular, does anybody know of an easy way I can get my component to wait a few seconds to make sure the call to the moratoriumService.PostMoratoriumLocationsArray() method finishes up before the navigateByUrl() kicks in on the router. Code is below. Any suggestions would be most appreciated. --Jason

 PostMoratoriumLocationsArray(moraID: any, moratoriumLocationsarray: MoratoriumLocation[]): Observable<any> {
    this.moratoriumService.PostMoratoriumLocationsArray(moraID, moratoriumLocationsarray)
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((data) => (this.moratoriumID) = (data),
        (error) => (console.log(error)),
        () => console.log('Post moratorium location for moratorium is complete'),
      );
    this.router.navigateByUrl('ActiveMoratoriums');
    return of(this.moratoriumID);
  }

this is async function you may not know how long server response. You should try below code

PostMoratoriumLocationsArray(moraID: any, moratoriumLocationsarray: MoratoriumLocation[]): Observable<any> {
    var subject = new Subject<string>();
    this.moratoriumService.PostMoratoriumLocationsArray(moraID, moratoriumLocationsarray)
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((data) => {
          (this.moratoriumID) = (data);
          this.router.navigateByUrl('ActiveMoratoriums');
           subject.next(data);
        },
        (error) => (console.log(error)),
        () => console.log('Post moratorium location for moratorium is complete'),
      );
      return subject.asObservable();
  }

How about building on the observable inside the pipe instead, and let the caller subscribe? Like this.

PostMoratoriumLocationsArray(moraID: any, moratoriumLocationsarray: MoratoriumLocation[]): Observable<any> {
    return this.moratoriumService.PostMoratoriumLocationsArray(moraID, moratoriumLocationsarray)
               .pipe(takeUntil(this.ngUnsubscribe),
                     tap(data => 
                         {
                             this.moratoriumID = data
                             this.router.navigateByUrl('ActiveMoratoriums');
                         },
                         error => console.log(error),
                         () => console.log('Post moratorium location for moratorium is complete'),
      ));
  }

And when you call the method, you do this: this.PostMoratoriumLocationsArray(...).subscribe()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM