注入器错误“提供程序解析错误:无法实例化循环依赖!”

2023-11-21

我尝试创建一个Http拦截器添加一些标头以对发生的每个 http 进行授权。我需要从名为的服务获取标头认证服务。下面是代码:

拦截器:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private auth: AuthService) { }
}

验证服务:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {
  constructor(private http: HttpClient) { }
}

应用程序模块:

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true,
  }, AuthService]

我收到以下错误:

错误:提供程序解析错误: 无法实例化循环依赖! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): 在 NgModule AppModule 中 在./AppModule@-1:-1

我已经检查了之前的答案,但我不明白在哪里检测到循环依赖。我正在尝试做的事情描述如下:https://angular.io/guide/http#setting-new-headers


看这个GitHub 讨论(问题#18224)

作为解决方法,您可以使用Injector手动并在里面注入相关服务intercept方法:https://github.com/angular/angular/issues/18224#issuecomment-316957213

我解决了简单地不在构造函数中设置 authService 但得到 在拦截函数中。

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth header from the service.
    const auth = this.inj.get(AuthenticationService);
    const authToken = auth.getAuthorizationToken();
    ...
}

UPDATE:

在 Angular 之前4.3.0不幸的是它无法使用Injector手动内部intercept方法:

ERROR Error: Uncaught (in promise): RangeError: Maximum call stack size exceeded

所以还有一种解决方法使用rxjs:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return Observable.create((observer: any) => {
        setTimeout(() => {
            const authService = this.injector.get(AuthenticationService)
            observer.next(authService.getAuthorizationHeader())
            observer.complete()
        })
    })
        .mergeMap((Authorization: string) => {
            let authReq = req

            if (Authorization) {
                authReq = req.clone({
                    setHeaders: {
                        Authorization
                    }
                })
            }

            return next.handle(authReq)
        })
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

注入器错误“提供程序解析错误:无法实例化循环依赖!” 的相关文章

随机推荐