我正在尝试将服务注入(inject) HttpInterceptor,这是简单的服务
import { Injectable } from '@angular/core';
@Injectable()
export class LoginLoadingService {
constructor() { }
public loaded: boolean;
isLoaded() {
if (this.loaded === undefined) {
this.loaded = true;
}
return this.loaded;
}
}
拦截器
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from
'@angular/common/http';
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { LoginLoadingService } from './loading.service';
import 'rxjs/add/operator/do';
@Injectable()
export class LoginLoadingInterceptor implements HttpInterceptor {
constructor(public loginLoadingService: LoginLoadingService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loginLoadingService.loaded = false
return next.handle(req).do((event: HttpEvent<any>) => {
this.loginLoadingService.loaded = true;
}, error => console.error(error));
}
}
在我的 app.module 中
providers: [
LoginLoadingService,
{
provide: HTTP_INTERCEPTORS,
useClass: LoginLoadingInterceptor,
multi: true
}
]
HttpInterceptor 运行正常,但 loginLoadingService 未在 intercept() 方法中定义。我试图将 deps 添加到 app.module 中的拦截器,但这给了我这个错误
params.map is not a function
不知道是什么问题
最佳答案
像下面这样定义拦截器的依赖关系:
例如,我们有AuthInterceptor
,我们注入(inject)了LocalStorageService
和SessionStorageService
。
在 app.module.ts 中我们添加拦截器 AuthInterceptor
:
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
deps: [LocalStorageService, SessionStorageService]
},
这会起作用。
关于angular - HttpInterceptor 中的注入(inject)服务未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49238907/