等待Angular 2中的Http响应 [英] wait for Http response in angular 2

查看:98
本文介绍了等待Angular 2中的Http响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在angular 2中使用HTTP请求.我想在收到HTTP响应后调用下一个进程.

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

示例:在表单 选择选项中,值来自 HTTP get Request .我要形成页面正在加载,直到我收到选择选项的响应为止.

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.

获取功能

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功能

 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.

如果使用map()而不是subscribe(),则可以返回创建的Observable供呼叫者订阅.如果您调用subscribe(),则返回值将是Subscription,但这通常对调用者不是很有用:

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

然后像这样使用它:

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

这篇关于等待Angular 2中的Http响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆