2016-11-29 56 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 –