HTTP拦截器无法正常工作的角度7

时间:2019-05-21 09:15:06

标签: javascript angular typescript http

我已将我的角度应用程序从4升级到最新版本7。经过如此多的错误后,我终于使它工作了,但现在出现了一个问题:服务无法正常工作,就像它在控制台中没有给出任何错误但没有工作正常。

我认为问题出在我的Http拦截器以及缺少某些东西的工厂。

有人可以确切地说出问题是什么吗?

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

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

应用程序模块中的提供商

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

每当我登录时,它就开始加载,没有其他内容,没有错误或任何东西,当我在应用程序模块中注释掉提供程序时,它说“ 404 not found error”。

有帮助吗?

谢谢

1 个答案:

答案 0 :(得分:0)

无法评论您在Angular 4中的拦截器的工作方式。但是自从引入了HttpInterceptor 4.3以来,下面是一个在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);
      })
    );
  }
}

这是一个拦截器的示例,该拦截器除了返回不变的请求外什么也不做:

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

如何提供:

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

您可以检查request对象,以检查请求类型(POST,GET)并执行所需的操作。

这可能是显而易见的(或不是显而易见的),但是HttpInterceptor 仅在有效时有效,是使用Angular 4.3中引入的HttpClient发出的。如果您的请求是由其他http客户端(HttpModule的旧客户端,本机代码或其他库)发出的,则AFAIK无效。

此外,如果您尝试延迟加载,拦截器将不会很简单(甚至不确定是否可能),因此请首先尝试使其工作。

相关问题