How does angular5 execute http requests like Synchronize?

/ / previous operation

/ / Asynchronous request

/ / later

in angular5, how can a process like this wait for the asynchronous request to finish executing before performing the next operation?

Mar.16,2021
The http request in
clipboard.png


angular is promise. You can string the operation with the asynchronous request


use callback, the following pseudo code

//

//
.success((//))

if it is cyclic asynchronous, you can use recursion

//

 A(){
    //
    .success((A()))
}

you can first encapsulate a layer of http requests, such as post (url, data = {}, headers = this.headers ()) {

url = this.handle(url);
return this.http.post(url, data, { headers: headers })
  .map(response => response.json())
  .catch(error => this.errorNotice(error));

}
then write the service or directly introduce postSomething (params: any): Observable {

const url = Constant.serverIp + Constant.api.someApi;
return this.DHttp.post(url, params).map(res => res);

}
Last subscription
this.postSomething (this.params) .subscribe (res= > {}, err= > {})


first of all, the http.get () / post () return type in angular is Observable < response > , not promise .

but Observable can be converted to promise, so this is to use async await to make the code look Synchronize.

  obsevable: Observable<Response> = this.http.get("url", {headers: headers});
  async testObservable() {
    //
    .....
    //
    let response: Response = await this.obsevable.toPromise();
    //
    .....
  }
Menu