如果成功,转换http请求/添加功能。 :: Typescript& Angular2

时间:2016-12-17 11:16:22

标签: javascript http angular asynchronous typescript

我有一个http请求:

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .subscribe(res => {
        this._values.push(res.json());
    }));
};

成功案例中,我想制作一行代码:

this.vars.map((v,i) => v.push(this._values[i].value));

我的问题在正常的ajax中就像.success: function(){}

如何将我的代码转换成这样的代码?

提前谢谢。

修改

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .subscribe(res => {
        this._values.push(res.json());
      })).then(console.log());
};

Angular2无法解析then变量。我有什么要导入到组件中以使其工作?

1 个答案:

答案 0 :(得分:1)

http函数使用observables。 你可以这样做:

 private getValues() {
      this._watchlistElements.map(v =>
        this.http.get('http://localhost/getValue/' + v.xid).map(res=>res.json())
          .subscribe(res => {
           //success
          },
         error=>{
             //error logic
          });
      }

如果您只想使用承诺,

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .toPromise()
      .then(res=>{res.json()}).catch(errorFunction);
};