Angular 如何在自定义类中注入依赖项?

Angular 如何在自定义类中注入依赖项?,angular,Angular,我正在使用拦截器,该拦截器创建自定义类的实例,如: @Injectable() export class LoggingInterceptor implements HttpInterceptor { constructor( @Inject('LOGGING_CONFIG') private config: iLoggingConfig ) {} intercept(req: HttpRequest<any>, next: HttpHandler) : Ob

我正在使用
拦截器
,该拦截器创建自定义类的实例,如:

@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);
  }

}

这可行吗?若有,;怎么做?

我不完全明白。我可能无法准确回答你的问题,但我会尽力的

什么是“ilogingconfig”?为什么要使用“日志记录配置”

“自定义类”是对象还是服务

1“根”服务解决方案

@Injectable({providedIn:'root'})//不需要添加到提供程序
导出类ILOGINGCONFIG{
// ...
}
导出类交互请求{
构造函数(私有配置:ilogingconfig){
log(this.config);
}
}
@NgModule({…,提供程序:[],…})
导出类AppModule{…}
2)模块服务解决方案

@Injectable()//您必须添加到要使用的任何模块中。
导出类ILOGINGCONFIG{
// ...
}
导出类交互请求{
构造函数(私有配置:ilogingconfig){
log(this.config);
}
}
//它可以是另一个模块,您只能在这个模块和子模块中看到它
//在本例中,我将其放入AppModule,这与我的第一个示例相同。
@NgModule({…,提供程序:[ilogingconfig],…})
导出类AppModule{…}
3)常量对象解决方案

export const ilogingconfig={…};
//或
export const ilogingconfig=new CustomClass();
从'path/to/i-logging-config.ts'导入{iLoggingConfig}
导出类交互请求{
构造函数(){
log(iLoggingConfig);
}
}

我不完全理解。我可能无法准确回答你的问题,但我会尽力的

什么是“ilogingconfig”?为什么要使用“日志记录配置”

“自定义类”是对象还是服务

1“根”服务解决方案

@Injectable({providedIn:'root'})//不需要添加到提供程序
导出类ILOGINGCONFIG{
// ...
}
导出类交互请求{
构造函数(私有配置:ilogingconfig){
log(this.config);
}
}
@NgModule({…,提供程序:[],…})
导出类AppModule{…}
2)模块服务解决方案

@Injectable()//您必须添加到要使用的任何模块中。
导出类ILOGINGCONFIG{
// ...
}
导出类交互请求{
构造函数(私有配置:ilogingconfig){
log(this.config);
}
}
//它可以是另一个模块,您只能在这个模块和子模块中看到它
//在本例中,我将其放入AppModule,这与我的第一个示例相同。
@NgModule({…,提供程序:[ilogingconfig],…})
导出类AppModule{…}
3)常量对象解决方案

export const ilogingconfig={…};
//或
export const ilogingconfig=new CustomClass();
从'path/to/i-logging-config.ts'导入{iLoggingConfig}
导出类交互请求{
构造函数(){
log(iLoggingConfig);
}
}

ilogingconfig
应该从导入我们的模块提供值,而不是类提供程序
ilogingconfig
应该从导入我们的模块提供值,而不是类提供程序
export class InteractionRequest {
  constructor(
    @Inject('LOGGING_CONFIG') private config: iLoggingConfig
  ) {
   console.log(this.config); // it logs undefined!!
  }
}