简体   繁体   中英

angular 4 observable catch service undefined

I have a service to work with the interact with the backend. The am looking to catch 401 status, indicating the user has been logged out by the backend (token expiration). So when I catch a 401, I save off the current route, and navigate 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);
}

}

Replace

catch(this.handleError)

by

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

Otherwise, you're not binding the handleError function to this .

Also note that the proper status code for your status would be 401, not 403.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM