Angular 2 - 无法实例化循环依赖

时间:2016-12-20 13:23:39

标签: javascript http angular typescript dependency-injection

我创建自定义XHRBackend类以全局捕获401错误。在AuthService中,我有两个使用http-login和refreshToken的方法。所以我有这样的依赖链:Http - > customXHRBackend - > AuthService - >断点续传。我该如何解决这个问题?

export class CustomXHRBackend extends XHRBackend {
  constructor(browserXHR: BrowserXhr,
              baseResponseOptions: ResponseOptions,
              xsrfStrategy: XSRFStrategy,
              private router: Router,
              private authService: AuthService) {
    super(browserXHR, baseResponseOptions, xsrfStrategy);
  }

  createConnection(request: Request): XHRConnection {
    let connection: XHRConnection = super.createConnection(request);
    connection.response = connection.response
      .catch(this.handleError.bind(this));

    return connection;
  }

  handleError(error: Response | any) {
    console.log('ERROR',error['status']);
    if(error['status'] === 401) {
      this.authService.logout();
      this.router.navigate(['/']);
    }

    return Observable.throw(error);
  }
}

AuthService.ts

@Injectable()
export class AuthService {
  private loggedIn: boolean = false;

  constructor(private http: Http) {
    this.loggedIn = !!localStorage.getItem('authToken');
  }

  login(email: string, password: string): Observable<Response> {
    let headers: Headers = new Headers();
    headers.set('Content-Type', 'application/json');

    return this.http.post('https://httpbin.org/post',
      {
        email: email,
        password: password
      },
      {
        headers: headers
      })
      .map((response) => {
        let res = response.json();

        // if (res['success']) {
        if (res) {
          localStorage.setItem('authToken', res['token']);
          localStorage.setItem('refreshToken', res['refreshToken']);
          console.log('logged');
          this.loggedIn = true;
        }

        return response;
      }
    );
  }

  logout(): void {
    localStorage.removeItem('authToken');
    this.loggedIn = false;

    console.log('Logged out');
  }

  isLogged(): boolean {
    return this.loggedIn;
  }

  refreshToken(): Observable<Response> {
    let headers: Headers = new Headers();
    headers.set('token', localStorage.getItem('token'));
    headers.set('refreshToken', localStorage.getItem('refreshToken'));

    return this.http.get('https://httpbin.org/get', {
      headers: headers
    });
  }

}

在app.module.ts中包含CustomXHRBackend

{
      provide: XHRBackend,
      useFactory: (browserXHR: BrowserXhr,
                   baseResponseOptions: ResponseOptions,
                   xsrfStrategy: XSRFStrategy,
                   router: Router,
                   authService: AuthService) => {
        return new CustomXHRBackend(browserXHR, baseResponseOptions, xsrfStrategy, router, authService);
      },
      deps: [BrowserXhr, ResponseOptions, XSRFStrategy, Router, AuthService]
    }

2 个答案:

答案 0 :(得分:0)

HTTP拦截器怎么样......有一篇博文here 如果你谷歌你会发现更多...... Here's如何将一个人挂钩到App Module中 您可以在拦截器中克隆请求并将X-CustomAuthHeader添加到标题等中。

答案 1 :(得分:0)

请在构造函数中查看注入依赖项的位置。您不能在几个服务中注入相同的依赖关系。例如:CustomXHRBackend => AuthService,AuthService => CustomXHRBackend