我有一个angular2组件,它使用一个Http用于发出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;
});
}
Run Code Online (Sandbox Code Playgroud)
该组件看起来像:
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;
});
}
Run Code Online (Sandbox Code Playgroud)
}
该服务返回组件订阅的Observable.但是,当error执行该函数时(由于HTTP请求返回非200状态代码),我将完整的HTTP响应对象作为error参数传递给错误处理函数.
如何在服务级别将其转换为仅返回该errorMessage部分?我想在错误处理函数中处理的是字符串错误消息,它不应该处理整个HTTP响应对象,甚至不知道HTTP是一个东西.
我已经习惯了Promises,仍然试图绕过RxJS.
您可以使用catch()运营商:
this.userRequest
.catch(e => Observable.throw(e.json().errorMessage))
// or just .catch(e => throw e.json().errorMessage)
.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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
324 次 |
| 最近记录: |