Wait for Http response in angular 2

I am using an HTTP request in angular 2. I want when I get an HTTP response, then the following process is called.

Example: In the form, select the option values โ€‹โ€‹come from HTTP get Request . I want to create a page loads until I get a response for selecting options.

get function

getSelectOptionValue(): any {
      let area_list_url = '/select_option_list/';

      this.urlGet(area_list_url).subscribe(
        (response) => {
          let data = response.text() ? response.json() : [{}];
          if (data) {
            Constant.areaList = data;
          }
        }
      );
    }
    return JSON.stringify(Constant.areaList);
  }

Get function

 urlGet(url: string) {

    return this._http.get(Constant.hostUrl + url, {headers: GlobalUtils.head})
      .map((res)=> {
        if (res.status === 200) {
          console.log(res);
          return res;
        } else if (res.status = 201) {
          return res;
        }
      }).catch((error)=> {
        console.log(error);

        if (error.status === 400) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 401) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 403) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 404) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 420) {
          return Observable.throw(new Error(error.status));
        } else {
          return Observable.throw(new Error(error.status));
        }
      });
  }
+4
source share
1 answer

You cannot force the code to wait for asynchronous calls to return.

What can you associate with asynchronous calls so that some code is executed when the asynchronous call returns.

map() subscribe(), Observable . subscribe(), Subscription, :

getSelectOptionValue():any {
      let area_list_url = '/select_option_list/';

      return this.urlGet(area_list_url).map( /// <<<=== use `map` here
        (response) => {
          let data = response.text() ? response.json() : [{}];
          if (data) {
            Constant.areaList = data;
          }
          return JSON.stringify(Constant.areaList);
        }
      );
    }
}

this.getSelectOptionValue().subscribe(data => {/* your code that works with received data here */ });
+10

Source: https://habr.com/ru/post/1658062/


All Articles