从角度HttpInterceptor使用服务

时间:2017-12-04 18:01:10

标签: angular singleton angular-http-interceptors

我正在尝试使用来自HttpInterceptor的单例服务,以便拥有一个自动忙碌加载指示器。

然而问题是拦截器在没有服务但没有使用服务的情况下工作。

我在HttpInterceptor的构造函数中引用了如下服务:

constructor(private htbs: HttpBusyService) {}

在app模块中,服务和HttpInterceptor的提供方式如下:

providers: [
    HttpBusyService,
    { provide: LocationStrategy, useClass: HashLocationStrategy},
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    MessageService,
    ConfirmationService,
]

我得到的错误是:

Uncaught Error: Can't resolve all parameters for AuthInterceptor: (?).
    at syntaxError (compiler.js:485)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15664)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15499)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15479)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15839)
    at eval (compiler.js:15750)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15710)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15278)
    at JitCompiler._loadModules (compiler.js:34226)

我不知道在哪里看。我显然做错了,因为我看到其他拦截器使用单身人士。 我使用角度5.1.0-rc.1但5.0.0有同样的问题

非常感谢任何帮助

PS1我见过Angular HTTP Interceptor that uses a Service?但答案没有帮助 PS2我尝试重新安排提供者

编辑:拦截器

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpResponse, HttpHandler, HttpEvent,     HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HttpBusyService } from './http-busy.service';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/Observable';
import 'rxjs/add/observable/throw';

export class AuthInterceptor implements HttpInterceptor {

  constructor(private htbs: HttpBusyService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<HttpEventType.Response>> {
  // this.htbs.start();
const authReq = req.clone({
  setHeaders: { 'X-AUTH-TOKEN': sessionStorage.getItem('token') }
});
return next
.handle(authReq)
.do((ev: HttpEvent<any>) => {
  if (ev instanceof HttpResponse) {
    console.log('processing response', ev);
  }
})
.catch(response => {
  // if (response instanceof HttpErrorResponse) {
    console.log('Processing http error', response);
  // }

  return Observable.throw(response);
});
  }
}

和忙碌的服务:

import { Injectable } from '@angular/core';

@Injectable()
export class HttpBusyService {
  public busy = false;
  private count = 0;
  constructor() { }
  public start() {
    this.count++;
    this.busy = true;
  }
  public finish() {
    this.count--;
    if (this.count <= 0) {
      this.count = 0;
      this.busy = false;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您忘记使用@Injectable() Decorator表示AuthInterceptor是可注射元素。

Angular Dependency Injection就是这样的。你应该定义任何&#34;注射&#34;组件使用@Injectable并在@Component提供程序中注册。为了增加理解,你应该阅读this

最后,根据我的拙见,有时候,Angular中的错误及其相关的调用堆栈有点难以理解,而且它们很有说服力