[英]Generic build request method response undefined
I created a generic build request method for all my api calls. 我为我的所有api调用创建了通用的构建请求方法。 The response comes in okay, but isn't passed outside of this method. 响应可以,但是未在此方法之外传递。
My api.ts class (snippet) 我的api.ts类(摘要)
buildRequest(url, method, body?) {
let options = new RequestOptions({
url: this.apiUrl + url,
method: method,
body: body
});
let req = new Request(options);
return this.http.request(req)
.map(res => {
res.json();
})
.catch(this.handleError);
}
handleError(error: any) {
return Observable.throw(error.message);
}
In the same class I have defined all the calls like so: 在同一个类中,我定义了所有调用,如下所示:
getItem() {
return this.buildRequest('url', RequestMethod.Get)
}
Then from a component I do 然后从一个组件
this.api.getItem().subscribe(res => {
this.item = res;
}
})
Everywhere else, but inside the .map, the res is undefined . 在.map内的其他任何地方,res都是undefined 。 When I used regular 当我用常规
return this.http.get(...) 返回this.http.get(...)
and the same logic displayed here, it worked fine. 并在此处显示相同的逻辑,效果很好。 What am I doing wrong? 我究竟做错了什么?
I am importing these two: 我要导入这两个:
import {Observable} from 'rxjs/Observable'; 从'rxjs / Observable'导入{Observable};
import 'rxjs/Rx' 导入'rxjs / Rx'
In your buildRequest
method you made a little mistake. 在您的buildRequest
方法中,您犯了一个小错误。 When using lambda expressions with curly braces, you have to return something: 当使用带有花括号的lambda表达式时,您必须返回以下内容:
x => x.Field // <-- this is a shorthand
equals 等于
x => { return x.Field; }
So your code in the .map
call should look like this: 因此, .map
调用中的代码应如下所示:
return this.http.request(req)
.map(res => {
return res.json();
})
.catch(this.handleError);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.