簡體   English   中英

Angular 9 - 無法實例化循環依賴! InjectionToken HTTP_INTERCEPTORS 即使使用注入器和 setTimeout()

[英]Angular 9 - Cannot instantiate cyclic dependency! InjectionToken HTTP_INTERCEPTORS even with injector and setTimeout()

有一個用於更新 JWT 令牌的攔截器,它使用帳戶服務和帳戶服務使用 http 客戶端調用服務器。

@Injectable()
export class TokenRenewalInterceptor implements HttpInterceptor {

    private accountService: AccountService;

    constructor(private injector: Injector) {
        this.accountService = this.injector.get(AccountService);
    }

    tokenRenewalInProgress: boolean = false;

    intercept(req: HttpRequest<any>, next: HttpHandler) {

        if (this.accountService.hasTokenExpired() &&
            !req.url.includes('/renewToken') &&
            !req.url.includes('/logout')) {

            console.log('token expired');

            if (!this.tokenRenewalInProgress) {
                console.log('renewing');

                this.tokenRenewalInProgress = true;
                this.accountService.renewToken();
                return this.accountService.tokenRenewalState
                    .pipe(
                        tap(() => {
                            this.tokenRenewalInProgress = false;
                        }),
                        switchMap(v => {
                            return next.handle(req);
                        })
                    )
            } else {
                console.log('waiting');

                return this.accountService.tokenRenewalState
                    .pipe(
                        switchMap(v => {
                            return next.handle(req);
                        })
                    )
            }
        }
        return next.handle(req);
    }
}

我嘗試使用injectorsetTimeout()但沒有運氣。 此代碼適用於我以前的 Angular 項目(版本 7 和 8)。

編輯:

@Dalorzo :我剛剛將項目升級到 Angular 10,仍然是同樣的錯誤。

@John Peters :運行 tsc 給了我命令行提示,沒有任何 output。 (我想這意味着沒有錯誤)

@Thierry Falvo :我也試過這個

intercept(req: HttpRequest<any>, next: HttpHandler) {

    const accountService = this.injector.get(AccountService);
    //...
}

這給了我一個稍微不同的錯誤:無法實例化循環依賴! 賬戶服務

這是帳戶服務構造函數:

constructor(private httpClient: HttpClient,
    private tokenService: TokenService,
    private router: Router)

目前我正在使用 Angular CLI 10.0.1並且該項目正在使用 Angular 包的~10.0.2版本。

@sasan 在構造函數中嘗試使用@forwardRef,如下所示。

constructor(@Inject(forwardRef(() => AccountService)) public accountService: AccountService) {
}

它可能會解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM