我有一个 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/