1
我有一个使用服务的angular2组件,它使用Http
来发出HTTP请求。如何在使用subscribe()处理之前转换Http错误?
服务看起来像:
export class AuthenticateService {
constructor(private http: Http) {}
public authenticateUser(username: string, password: string) : Observable<User> {
return this.http.post("http://localhost:3002/admin/login", {
username: username, password: password
})
.map((res: Response) => {
//I can fiddle with non-error responses here, but if an error happens then this doesnt get called
return res.json() as User;
});
}
和组件看起来像:
export class LoginFormComponent {
userRequest : Observable<User>;
constructor(private _authenticateService: AuthenticateService, private _router: Router) {}
doLogin() : void {
this.userRequest = this._authenticateService.authenticateUser(this.form.username, this.form.password);
this.userRequest.subscribe(user => {
this._router.navigateByUrl("/user");
}, error => {
//this is where I just want the 'errorMessage' property, not the entire ResponseBody object
console.log("Error object looks like: ", error);
this.errorMessage = error.json().errorMessage;
});
}
}
服务会返回一个可观察该组件订阅。但是,当执行error
函数时(由于HTTP请求返回非200状态码),我得到了作为error
参数传递给错误处理函数的完整HTTP响应对象。
如何在服务级别转换它以返回errorMessage
部分?我想在我的错误处理函数中处理的是字符串错误消息,它不应该处理整个HTTP响应对象,甚至不知道HTTP是一件事情。
我已经习惯承诺,仍然试图让我的头绕RxJS。
我想这应该是'.catch(E => Observable.throw(e.json()的errorMessage)' – estus
应该甚至'。 catch(resp => Observable.throw(resp.json()。errorMessage))',做什么OP想要的,如果我没有弄错的话 –
取决于你想要完成的事情,但我同意它没有在这种情况下使''error => {...}'成为非常有意义的东西。感谢提示。 –