Isa*_*vin 6 angular-http-interceptors angular
我试图将服务注入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;
}
}
Run Code Online (Sandbox Code Playgroud)
和拦截器
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));
}
}
Run Code Online (Sandbox Code Playgroud)
在我的app.module中
providers: [
LoginLoadingService,
{
provide: HTTP_INTERCEPTORS,
useClass: LoginLoadingInterceptor,
multi: true
}
]
Run Code Online (Sandbox Code Playgroud)
HttpInterceptor正常运行,但是在intercept()方法中没有定义loginLoadingService.我试图在app.module中向拦截器添加deps,但这给了我这个错误
params.map不是一个函数
不知道这里的问题是什么
Had*_*uli 23
为拦截器定义依赖关系,如下所示:
例如AuthInterceptor,我们已经注入了LocalStorageService和SessionStorageService.
在app.module.ts中我们添加了拦截器AuthInterceptor:
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
deps: [LocalStorageService, SessionStorageService]
},
Run Code Online (Sandbox Code Playgroud)
这会奏效.
@Hadi 提供的答案是正确的。我想我会补充的。本文详细解释了在 app 模块中使用deps的原因。 https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html#new-staticinjector-apis
较新版本的 Angular 使用了 StaticInjector,其中 Angular 的 DI 框架发挥了作用。我们基本上要求 Angular 在需要时通过将它们作为提供者注入app.module来为我们提供服务的单例实例。
这只不过是{provide: token_name, useClass:class_name}的简写版本
所以我们请求 angular 使用上面的代码注入一个类型(类)的令牌。现在,如果我们需要将令牌注入现有的服务依赖项,那么我们要求像这样注入令牌
{提供:token_name,useClass:class_name,deps:[deps_name]}
这就是为什么,下面解析拦截器的静态注入
{ 提供: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, deps: [LocalStorageService, SessionStorageService] },
| 归档时间: |
|
| 查看次数: |
4310 次 |
| 最近记录: |