将Angular 4升级到7时服务无法正常工作

时间:2019-05-20 10:04:45

标签: angular typescript http service angular-http-interceptors

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

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

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

Http拦截器

  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)

这些版本之间发生了几次更改,不需要太多工作,我也去过那里。

这里是一个助手,选择原始版本和目标,您将获得有关所需更改的逐步指导。

update.angular.io