2016-11-29 78 views
2

router.navigate中的HandleError功能錯誤後發生無法正常工作如何處理4xx錯誤與router.navigate可觀察。角2

可觀測方法

getAll(): Observable<any[]> { 
    return this._http.get('/api/getall') 
     .map((response: Response) => <any[]>response.json()) 
     .do(data => console.log("All: " + JSON.stringify(data))) 
     .catch(this.handleError); 
} 

處理錯誤方法

private handleError(error: any) { 
    if (error.status === 401) {  
    this._router.navigate(["/login"]);    
    { 
    return Observable.throw(error.json().error || 'Server error'); 
    } 
} 

回答

1

後我改變

.catch(this.handleError.bind(this)); 

.catch<any[]>(this.handleError.bind(this)); 

這項工作正常

感謝@君特 - zöchbauer

3

如果你想使用handleErrorthis你需要以不同的方式傳遞功能

getAll(): Observable<any[]> { 
    return this._http.get('/api/getall') 
     .map((response: Response) => <any[]>response.json()) 
     .do(data => console.log("All: " + JSON.stringify(data))) 
     .catch(this.handleError.bind(this)); 
     // .catch(err => this.handleError(err)); 
} 
+1

感謝,但是當我加入」 .catch(this.handleError .bind(this))「,發生以下錯誤: type observable <{}{>不是屁股可以鍵入可觀察的。 type {}不可分配爲布爾類型 @günter-zöchbauer –