我从去年开始学习角度,就偶然发现了角度依赖注入。情况是我需要注入需要实例化某些参数的依赖项。目前,我正在这样做:
some-dependency.service.ts
import { Injectable } from '@angular/core';
import { ConfigService } from 'app/services/config.service';
import { Client } from 'some-dependency';
@Injectable({
providedIn: 'root',
useFactory: (config:ConfigService) => new Client({
host:config.clientURL, maxRetries: config.maxRetry
}),
deps: [ConfigService]
})
export class SomeDependencyService extends Client {
}
another-service.service.ts
import { Injectable } from '@angular/core';
import { SomeDependencyService } from 'app/services/some-dependency.service';
@Injectable({
providedIn: 'root'
})
export class SomeService {
constructor( private deps: SomeDependencyService ) {}
getSomething() {
return this.deps.get('something');
}
}
代码运行良好,并且我可以在不将其实例化为Client
的情况下毫无问题地获取another-service.ts
实例,而且我可以轻松地对其进行模拟以进行单元测试,但是我不确定这是否是执行DI的正确方法带有Angular中的参数,我也不确定此代码是否会生成任何意外行为。
虽然我可以将依赖项导入需要它的服务内部,并在本地实例化该依赖项,但是如果我有很多需要依赖项的服务(和组件),那将非常烦人。
感谢
如果您可以控制ConfigService
,则可以使用注入令牌来注入配置。然后,配置服务看起来与此类似:
export interface Config {
clientURL:string;
maxRetry:number;
}
export const CONFIG_TOKEN:InjectionToken<Config> = new InjectionToken<Config>();
@Injectable({ providedIn: 'root' })
export class ConfigService {
constructor(@Inject(CONFIG_TOKEN) config: Config) {}
}
以及您的NgModule
@NgModule({
providers: [
{
provide: CONFIG_TOKEN,
useValue: config // this is your actual config Object containing clientURL and maxRetry
}
]
// ...
})