简体   繁体   中英

Http interceptors are not working angular 7

I have upgraded my angular app from 4 to latest version 7. After so many errors I finally got it to work but now there is one problem: services are not working, like it is not giving any error in the console but not working as well.

I think the problem is with my Http interceptor and the factory in which I am missing something.

Can someone tell me what the issue is, exactly?

Http interceptor

  export class InterceptedHttp extends HttpClient
  constructor(
    backend: HttpBackend,
    private store: Store<any>,
    private spinnerService: SpinnerService
  ) {
    super(backend);
  }

  request( url: string | HttpRequest<any>, options?: any): Observable<any> {
    this.showLoader();
    return this.tryCatch(super.request(this.getRequestOptionArgs(options)))
  }

  get(url: string, options?: any): Observable<any> {
    url = this.updateUrl(url);
    return this.tryCatch(super.get(url));
  }

  post(url: string, body: string, options?: any): Observable<any> {
    url = this.updateUrl(url);
    return this.tryCatch(
      super.post(url, body)
    );
  }

  put(url: string, body: string, options?: any): Observable<any> {
    url = this.updateUrl(url);
    return this.tryCatch(
      super.put(url, body)
    );
  }

  delete(url: string, options?: any): Observable<any> {
    url = this.updateUrl(url);
    return this.tryCatch(super.delete(url));
  }

  patch(url: string, body: any, options?: any): Observable<any> {
    url = this.updateUrl(url);
    return this.tryCatch(
      super.patch(url, body)
    );
  }

  private updateUrl(req: string) {
    return environment.origin + req;
  }

  private getRequestOptionArgs(options?: any): any {
    if (options.headers == null) {
      options.headers = new HttpHeaders();
    }
    options.headers.append('Content-Type', 'application/json');
    options.headers.append(
      'Authorization',
      ` Bearer ${sessionStorage.AccessToken}`
    );

    return options;
  }

  private tryCatch(obs: Observable<any>) {
    return obs.pipe(catchError((error: HttpResponse<any>, caught) => {
      if (error.status === 401 && sessionStorage.AccessToken) {
        sessionStorage.clear();
        this.store.dispatch({type: 'LOGOUT'});
      }
      this.hideLoader();
      return observableThrowError(error);
    }));
  }

Http factory

export function httpFactory(xhrBackend: HttpXhrBackend,
  store: Store<any>, spinnerService: SpinnerService): HttpClient {
  return new InterceptedHttp(xhrBackend, store, spinnerService);
}

provider in app module

 {
   provide: HttpClient,
   useFactory: httpFactory,
   deps: [HttpXhrBackend, Store, SpinnerService]
 },

Whenever I login it just starts loading, nothing else, no error or anything and when I comment out the provider in the app module it says "404 not found error".

Any help?

Thanks

Can't comment on how you did interceptors in Angular 4. But since 4.3 HttpInterceptor was introduced so here is an example on how you do http interceptors in Angular 7:

@Injectable()
export class ApiInterceptor implements HttpInterceptor {
  constructor(private someService: SomeService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return this.someService.getBaseUrl().pipe(
      mergeMap(baseUrl => {
        const apiRequest = data
          ? request.clone({ url: `${baseUrl}${request.url}` })
          : request;

        return next.handle(apiRequest);
      })
    );
  }
}

Here is an example of a intercept that does nothing but returning the request unchanged:

intercept(
     request: HttpRequest<any>,
     next: HttpHandler
): Observable<HttpEvent<any>> {
     return next.handle(request);
});

How to provide it:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
// ...
providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true }
]

You can inspect the request object to check the request type (POST, GET) and do what ever you want with it.

This might be obvious (or not) but HttpInterceptor only works if your requests are made with the HttpClient introduced in Angular 4.3. If your requests are made by other http client (the older client from HttpModule, native code or other library) it will not work, AFAIK.

Also if you try to lazy load the interceptor it will not be straightforward (not even sure if its possible), so first try to get it to work like this.

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