简体   繁体   English

以角度 2 等待 Http 响应

[英]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.我在 angular 2 中使用 HTTP 请求。我希望当我获得 HTTP 响应时调用下一个进程。

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.示例:表单中选择选项值来自HTTP get Request 。我想表单页面正在加载,直到我得到选择选项的响应。

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

You can't make code wait for async calls to return.您不能让代码等待异步调用返回。

What you can do 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.如果您使用map()而不是subscribe()您可以返回创建的Observable供调用者订阅。 If you call subscribe() the return value will be a Subscription but that is usually not very useful for the caller:如果你调用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);
        }
      );
    }
}

And then use it like:然后像这样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM