javascript - 转换http请求/如果成功则添加一个函数.::Typescript & Angular2

标签 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 变量。我需要将什么导入到组件中才能使其正常工作?

最佳答案

http 函数使用可观察量。 你可以这样做:

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

如果您只想使用 promise ,

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

关于javascript - 转换http请求/如果成功则添加一个函数.::Typescript & Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41197993/

相关文章:

javascript - 从另一个子窗口获得焦点子窗口

django - 在 Django 处理大请求时维持 http 连接(20 分钟以上)

javascript - Angular 6 解析始终未定义

javascript - Angular UI 路线状态未显示

java - 我想在一个组合中选择值,另一个组合将填充在同一页面上

javascript - 使用 jquery load() 加载 div 并更改 url

node.js - 用于微服务的 REST 消息传递层是否足够快?

http - 为什么 OkHttp 不重用它的连接?

javascript - 动画 ngIf 时元素重叠

angular - 如何使用 ng-sidebar 让 SidebarModule 在菜单按钮上推送内容?