0

As written above, I want to use a Service, which is injected in root, in a function to logout the user after an 401 error. The function is called in a pipe after an error occured in one of my http requests. Unfortunately I get an error like:
ERROR TypeError: Cannot read property 'logout' of undefined
after an 401 error. It seems like the function is called in a different scope. I tried to inject the Service via injector.get, to set my service and the error function to public but nothing worked.
Is there any other opportunity to fix this?

constructor(private httpClient: HttpClient, private authenticationService: AuthenticationService) {}

private handleError(error: HttpErrorResponse) {
  if (error.status === 401) {
    this.authenticationService.logout();
  }
  return throwError('Something bad happened; please try again later.');
}

getSomething(): Observable<HttpResponse<Model>> {
  return this.httpClient.get<Model>(this.apiEndpoint, {
    observe: 'response'
  }).pipe(
  catchError(this.handleError)
  );
}
S14p
  • 51
  • 1
  • 7

2 Answers2

0

Without a working example it is a bit hard to troubleshoot, but I assume since you are passing the function directly, the function will not be executed in the this context of your class/component and therefore the service is probably undefined. A "fat arrow function" will most likely solve this problem.

Change your code like this:

getSomething(): Observable<HttpResponse<Model>> {
  return this.httpClient.get<Model>(this.apiEndpoint, {
    observe: 'response'
  }).pipe(
  catchError(err => this.handleError)
  );
}

Have a look at this post for more information.

Fabian Küng
  • 5,925
  • 28
  • 40
  • unfortunately it doesnt work: Argument of type '(err: any) => (error: HttpErrorResponse) => Observable' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput<{}>' I'll try to build it on stackblitz – S14p Dec 13 '18 at 09:02
0

Its a this context issue. Either you can use fat arrow function or bind handleError function with service context.

getSomething(): Observable<HttpResponse<Model>> {
  return this.httpClient.get<Model>(this.apiEndpoint, {
    observe: 'response'
  }).pipe(
  catchError(this.handleError.bind(this))
  );
}
Praveen Gupta
  • 246
  • 1
  • 5