Angular 4 observable method catch undefined

I have a service to work with backend communication. I am looking to catch a 401 status indicating that the user is logged out using the backend (token expiration). So when I catch 401s I save the current route and move them to the login page. However, when I catch the error, the router service is undefined. Is this something to do with observables?

@Injectable()
export class SiteService {
private url : string = "site";
constructor(
    private http: Http, 
    private authService : AuthenticationService,
    private router : Router,
    private globals : Globals
    ){}

addSite(site : Site) : Observable<Site> {
    let data = new URLSearchParams();
    data.append('auth', this.authService.getToken());
    const options = new RequestOptions({
        params: data
    });
    return this.http.post(this.url, site, options).map(response => {
        return toSite(response.json().data);
    }).catch(this.handleError);

}
changeSite(site : Site) : Observable<Site> {
    let data = new URLSearchParams();
    data.append('id', this.authService.getToken());
    const options = new RequestOptions({
        params: data
    });
    return this.http.post(`${this.url}/${site.siteName}`, site, options).map(response => {
        return toSite(response.json().data);
    }).catch(this.handleError);
}


private handleError(error : any) {
    let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg);
    if((error.status == 403 || error.status == 401) &&(error.json().error.indexOf("token") >= 0)){
        this.globals.nextLocation = this.router.url;
        this.router.navigate(['login']);
    }
    return Observable.throw(error);
}

      

}

+3


source to share


1 answer


Replace

catch(this.handleError)

      

by



catch(error => this.handleError(error))

      

Otherwise, you don't bind the handleError function to this

.

Also note that the correct status code for your status will be 401, not 403.

+5


source







All Articles