我通常不订阅服务,而是订阅组件。但这是我在身份验证服务中的代码。
getUser(userId: string) {
const token = localStorage.getItem('token');
const headers = new Headers({'Authorization': token});
return this._http.get('http://localhost:3000/user/' + userId, {headers: headers})
.map(response => {
const data = response.json().obj;
let user = new User (data.email, data.password,
data.firstName, data.lastName,
data.messages);
return user;
})
//.catch(error => Observable.throw(error.json()));
.catch((err) => this.handleError(err));
}
private handleError(error: Response) {
if(error.status == 403 ){
console.error(error + 'Session over. Please log in to continue.');
}
console.error(error + 'Session over. Please log in to continue.');
this._router.navigate(['/']);
this.logout();
return Observable.throw(error.json().error || "Server error");
}
在我的组件中,它应该是:
this.http.getUser(string: string)
.subscribe(
result => { this.result = result;
},
error => { console.log('raw error =>', err);
});
让我知道我是否可以成为你的助手。