user6751153 user6751153 - 1 month ago 19
TypeScript Question

wait for Http response in angular 2

I am using HTTP request in angular 2. I want when I get HTTP response then next process is called.

Example: In a form select option values are coming from HTTP get Request.I want to form page is loading until I get response for select 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));
}
});
}

Answer

You can't make code wait for async calls to return.

What you can to is to chain async calls, so that when an async call returns, some of your code is executed.

If you use map() instead of subscribe() you can return the created Observable for the caller to subscribe. If you call subscribe() the return value will be a Subscription but that is usually not very useful for the caller:

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

and then use it like

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