简体   繁体   English

Http拦截器没有工作角7

[英]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. 我已经将我的角度应用程序从4升级到最新版本7.经过这么多错误我终于得到了它的工作,但现在有一个问题:服务不起作用,就像它没有在控制台中给出任何错误但是没有正常工作。

I think the problem is with my Http interceptor and the factory in which I am missing something. 我认为问题出在我的Http拦截器和我失踪的工厂。

Can someone tell me what the issue is, exactly? 有人可以告诉我这是什么问题吗?

Http interceptor Http拦截器

  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 Http工厂

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

provider in app module app模块中的提供者

 {
   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". 每当我登录它只是开始加载,没有别的,没有错误或任何东西,当我在应用程序模块中注释掉提供程序时,它说“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: 无法评论你是如何在Angular 4中做拦截器的。但是自从引入了4.3 HttpInterceptor所以这里是一个关于如何在Angular 7中进行http拦截的例子:

@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. 您可以检查request对象以检查请求类型(POST,GET)并使用它执行任何操作。

This might be obvious (or not) but HttpInterceptor only works if your requests are made with the HttpClient introduced in Angular 4.3. 这可能是显而易见的(或不是),但只有在使用Angular 4.3中引入的HttpClient进行请求时,HttpInterceptor 才有效 If your requests are made by other http client (the older client from HttpModule, native code or other library) it will not work, AFAIK. 如果您的请求是由其他http客户端(来自HttpModule的旧客户端,本机代码或其他库)提出的,那么它将不起作用,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. 此外,如果你试图延迟加载拦截器,它将不会直截了当(甚至不确定它是否可能),所以首先尝试让它像这样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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