为什么服务中的响应可用但组件中的响应未定义?

时间:2017-10-26 08:40:22

标签: json angular typescript observable

我有一个服务和一个使用该服务的组件。问题是在服务中我可以读取作为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;
        }
    );
}

1 个答案:

答案 0 :(得分:2)

您的问题似乎与此代码有关:

.map(res => {
    res.json();
})

您未返回res.json的结果。您只需要添加return语句,如下所示:

.map(res => {
    return res.json();
})

您也可以删除{}对,如下所示:

.map(res => res.json())