voliva / angular2-interceptors

79 stars 20 forks source link

Nothing happens when making HTTP request #3

Closed maxime1992 closed 7 years ago

maxime1992 commented 7 years ago

Hi, I really like the idea of interceptors.

I need that in an app to catch 401 and redirect to /login.

Here's what I did so far :

providers: [
    provideInterceptorService([
      HttpResponseInterceptor
    ])
]
import { Injectable } from '@angular/core';
import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';

@Injectable()
export class HttpResponseInterceptor implements Interceptor {
  constructor() {
    console.log('Created');
  }
  public interceptBefore(request: InterceptedRequest): InterceptedRequest {
    // Do whatever with request: get info or edit it
    console.log('request start');
    return request;
    /*
     You can return:
     - Request: The modified request
     - Nothing: For convenience: It's just like returning the request
     - <any>(Observable.throw("cancelled")): Cancels the request
     */
  }

  public interceptAfter(response: InterceptedResponse): InterceptedResponse {
    // Do whatever with response: get info or edit it
    console.log('request ended');

    return response;
    /*
     You can return:
     - Response: The modified response
     - Nothing: For convenience: It's just like returning the response
     */
  }
}

When I make an http request :

public connectUser(user: IUser): Observable<Response> {
  return this.http
    .post(`${environment.urlBackend}/user/session`, user);
}

I do not have request start or request ended displayed.

What am I missing ?

Thanks

voliva commented 7 years ago

Could be that this.http is being injected as the vanilla Http service? What's your constructor signature on the controller? To inject the Interceptor service, it should be like:

contructor(private http:InterceptorService){
}

public connectUser(user: IUser) [....]

Also, it's not related to this issue, but remember that you also need to delcare the provider for your HttpResponseInterceptor service, so if you haven't, in your app module you should put something like:

providers: [
    HttpResponseInterceptor,
    provideInterceptorService([
      HttpResponseInterceptor
    ])
]
maxime1992 commented 7 years ago

Oh I must be tired ... I did inject Http instead of InterceptorService. It works perfectly ! Thanks. And I forgot to add the providers because I created a class first and then I turned this class into a service :).

Thanks for helping me, cheers ! :+1: