mod*_*777 8 dependency-injection swagger-codegen angular
我收到一个奇怪的DI错误.这是来自swagger-codegen的一段自动生成的代码 - 我无法改变它.我正在尝试注入这项服务.但是当我跑步时,ng build --aot我得到Can't resolve all parameters...DI错误.
我试图完全删除脚趾@Optional参数,它似乎工作.所以这似乎是罪魁祸首.
我的问题:如果参数不可选,为什么我会收到错误?如果我想实际注入这个参数,我也会感兴趣,因为它是一个原始类型.
@Injectable()
export class MyApi {
protected basePath = 'https://localhost/';
public defaultHeaders : Headers = new Headers();
constructor(protected http: Http, @Optional() basePath: string) {
if (basePath) {
this.basePath = basePath;
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:@Nildari和@PierreDuc的答案可能是大多数人可能正在寻找的答案.但是,我正在寻找一种解决方案,它不会改变原始实现,因为它是自动生成的.
您需要使用InjectionToken:
export const BASE_PATH: InjectionToken<string> = new InjectionToken<string>('basePath');
// note that the string value `basePath` is just a description of the `InjectionToken`
// and not actually the base path.
Run Code Online (Sandbox Code Playgroud)
使用的优点InjectionToken
然后您需要将一个提供对象添加到您的providers数组中NgModule:
@NgModule({
//...
providers: [
{provide: BASE_PATH, useValue: '/'}
]
})
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下命令将此提供程序注入到您的服务中@Inject:
constructor(protected http: Http, @Inject(BASE_PATH)basePath: string) {
if (basePath) {
this.basePath = basePath;
}
}
Run Code Online (Sandbox Code Playgroud)
@Optional如果你愿意的话,你可以添加装饰器..但是如果你将它添加到你的providers数组中,它总是会被找到
| 归档时间: |
|
| 查看次数: |
1155 次 |
| 最近记录: |