如何在使用subscribe()处理之前转换Http错误?

时间:2016-11-06 10:44:30

标签: angular rxjs

我有一个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;
    }); 
  }

该组件看起来像:

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;
    });
}

}

该服务返回组件订阅的Observable。但是,当执行error函数时(由于HTTP请求返回非200状态代码),我将完整的HTTP响应对象作为error参数传递给错误处理函数。 / p>

如何在服务级别将其转换为仅返回errorMessage部分?我想在错误处理函数中处理的只是字符串错误消息,它不应该处理整个HTTP响应对象,甚至不知道HTTP是一个东西。

我已经习惯了Promises,仍然试图绕过RxJS。

1 个答案:

答案 0 :(得分:5)

您可以使用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;
});