mohamad javad Taherian
mohamad javad Taherian

Reputation: 259

How to handle 4xx errors with router.navigate in observable. angular 2

router.navigate in handleError function after error occurred not work

Observable method

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

handle error method

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

Upvotes: 4

Views: 1458

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658225

If you want to use this in handleError you need to pass the function differently

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

Upvotes: 4

mohamad javad Taherian
mohamad javad Taherian

Reputation: 259

after i change

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

to

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

this work properly

thanks @günter-zöchbauer

Upvotes: 1

Related Questions