我有一个服务和一个使用该服务的组件。问题是在服务中我可以读取作为JSON对象的响应。但是在Component中,我得到以下内容:res: undefined
。
服务
constructor(
private http: Http,
private fbuilder: FormBuilder,
private user: UserService
) {}
login(uname:string, pass:string): Observable<any> {
let headers = new Headers({
'Content-Type': 'application/json',
'Username':uname,
'Password':pass
});
let options = new RequestOptions({ headers: headers });
let data = {};
var Observable = this.http.post( url, data, options )
.map(res => {
res.json();
})
.catch( (error: any) => Observable.throw(error.json().error || 'Server error') );
return Observable;
}
组件:
constructor(
private http: Http,
private fbuilder: FormBuilder,
private user: UserService
) {}
loginUser(uname: string, pass: string) {
this.user.login(uname, pass).subscribe(
res => {
console.log('res: ' + JSON.stringify(res));
},
err => {
this.errorMessage = err;
}
);
}
答案 0 :(得分:2)
您的问题似乎与此代码有关:
.map(res => {
res.json();
})
您未返回res.json
的结果。您只需要添加return
语句,如下所示:
.map(res => {
return res.json();
})
您也可以删除{}
对,如下所示:
.map(res => res.json())