我正在研究Interceptor
,它创建了一个自定义类的实例,例如:
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
constructor(
@Inject('LOGGING_CONFIG') private config: iLoggingConfig
) {}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> {
// get event that caused request
var event = <MouseEvent>window.event;
// check if there's no event
if (event === undefined) return next.handle(req);
// create request document
var requsetDocument = new InteractionRequest(this.config, req, event);
// set request document
this.service.setRequest(requsetDocument);
// continue request
return next.handle(req);
}
}
InteractionRequest
需要此对象的地方,而我在每个地方都必须注入config
的不同地方使用该类。
所以,我想如果我可以直接将配置注入InteractionRequest
类中,以免将其作为参数传递。
我试图注入类构造函数,但是它给了我undefined
,例如:
export class InteractionRequest {
constructor(
@Inject('LOGGING_CONFIG') private config: iLoggingConfig
) {
console.log(this.config); // it logs undefined!!
}
}
那可行吗?如是;怎么做?
答案 0 :(得分:0)
我不完全了解。我可能无法完全回答您想要的内容,但是我会尽力的。
什么是“ iLoggingConfig”?为什么要使用“ LOGGING_CONFIG”?
“自定义类”是对象还是Serivce?
1)“根”服务解决方案 https://angular.io/guide/providers
@Injectable({ providedIn: 'root' }) // not need add to providers
export class iLoggingConfig {
// ...
}
export class InteractionRequest {
constructor(private config: iLoggingConfig) {
console.log(this.config);
}
}
@NgModule({..., providers: [], ...})
export class AppModule {...}
2)模块服务解决方案
@Injectable() // not need add to providers
export class iLoggingConfig {
// ...
}
export class InteractionRequest {
constructor(private config: iLoggingConfig) {
console.log(this.config);
}
}
@NgModule({..., providers: [iLoggingConfig], ...})
export class AppModule {...}
3)const对象解决方案
export const iLoggingConfig = {...};
// or
export const iLoggingConfig = new CustomClass();
import { iLoggingConfig } from 'path/to/i-logging-config.ts
export class InteractionRequest {
constructor() {
console.log(iLoggingConfig);
}
}