2016-11-06 75 views
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。

回答

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

我想這應該是'.catch(E => Observable.throw(e.json()的errorMessage)' – estus

+0

應該甚至'。 catch(resp => Observable.throw(resp.json()。errorMessage))',做什麼OP想要的,如果我沒有弄錯的話 –

+0

取決於你想要完成的事情,但我同意它沒有在這種情況下使''error => {...}'成爲非常有意義的東西。感謝提示。 –