Search code examples
angularobservableangular2-services

Base service undefined when trying to handle an error, Angular


I have a service that extends a base service for to handle error data.

For example

import { CurrentUserService } from './current-user.service';
import { CONFIG } from './../shared/base-urls';
import { BaseServiceService } from './base-service.service';
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, ResponseContentType } from '@angular/http';
import { Router } from '@angular/router';

let baseUrl = CONFIG.baseUrls.url;

@Injectable()
export class ChildService extends BaseServiceService {

   constructor(
      public _http: Http,
      public _currentUser: CurrentUserService, 
      public _router: Router) 
   {
      super(_router, _http, _currentUser);
   }

   getFaqData() {
      var headers = new Headers();
      this.token = this._currentUser.getProfile().token;
      let sessionId = this._currentUser.getProfile().sessionId;
      headers.append('Authorization', `Bearer ${this.token}`);
      headers.append('Content-Type', 'application/json; charset=utf-8');
      return this._http.get(baseUrl + "api/UserAdmin/GetFaq", { headers: headers })
         .map((response: Response) => response.json())
         .catch(this.handleError)
   }
}

When there is an error this.handleError is called when located in the baseservice but when trying to use an instance in the base service for example to redirect a user when 401 error then the reference in the base service is null.

See below, get error cannot read the property 'navigate' of undefined

   //Inside BaseServiceService 

   constructor(
      public _router: Router, 
      public _http: Http, 
      public _currentUser: CurrentUserService) 
   {}

   protected handleError(response: Response):any {
      var message = "";
      if (response.status == 401) {  
        //cannot read the property 'navigate' of undefined   
        this._router.navigate(["/login", false]);
      }
      return Observable.throw(message || 'We apologise. There was a technical error processing the request. Please try again later.')
   }

How can I rectify this?


Solution

  • you have a this reference issue, while you are passing a function inside the catch function, this is not referencing the object anymore, you have to either use an arrow function, and call handleError inside it,

    catch((err)=>this.handleError(err)) //it will save the context
    

    or using bind method

       catch(this.handleError.bind(this)) it will do the same