Jason Livengood
Jason Livengood

Reputation: 127

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);
  }

Upvotes: 0

Views: 149

Answers (2)

ShamPooSham
ShamPooSham

Reputation: 2379

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()

Upvotes: 0

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17570

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();
  }

Upvotes: 1

Related Questions