简体   繁体   中英

Angular/RXJS - Wait for AJAX request to complete

export class DropDownService {
    private dockerURL;
     constructor(private infoService: InfoService){
            this.infoService.getVersion().subscribe((URL) => {
                 this.dockerURL = URL;
             });
            // How to make sure the dockerURL is loaded
            // before getStructureType is invoked from other services
    }
   getStructureType(): Observable<StructureType[]> {
       return this.http.get<StructureType[]>(this.dockerURL+'/structureType');
    }
}

How to make sure dockerURL is loaded before getStructureType is invoked from other services?

You can take advantage of switchMap for this.

Something like this:

import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
.....
export class DropDownService {
    private dockerURL;
     constructor(private infoService: InfoService){

     }

   getStructureType(): Observable<StructureType[]> {
       return this.getDockerURL().pipe(
          switchMap(url => {
             return this.http.get<StructureType[]>(url+'/structureType');
          }),
       );
    }

  private getDockerURL(): Observable<string> {
    if (this.dockerURL) {
      return of(this.dockerURL);
    } else {
      return this.infoService.getVersion().pipe(
       // tap is an operator that is used for side effects, every time this stream emits, we assign it to this.dockerURL. Should only be once.
       tap(url => this.dockerURL = url),
      );
    }
  }
}

This way, it ensures that dockerURL gets populated before making HTTP call.

Subscribe comes with err and success function callbacks. You can call getStructureType in success callback. The success callback gets called only when the request is complete.

this.infoService.getVersion().subscribe((URL) => {
       //...
   },
    err => { //========> if fails this gets called
        console.log(err );
    }
    suc => { // =======> gets called on success when its successfully executed
       this.dockerURL = URL;
       this.http.get<StructureType[]>(this.dockerURL+'/structureType');
    }
);

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