gpt4 book ai didi

Angular2 没有服务提供者 - 外部模块

转载 作者:太空狗 更新时间:2023-10-29 18:16:17 25 4
gpt4 key购买 nike

我构建了一个 Angular Module,它有自己的服务和组件:

@NgModule({
declarations: [ FileUploader],
exports: [ FileUploader ],
imports: [ CommonModule ],
providers: [ FileService ],
})
export class FilesModule { }

文件服务:

import { Injectable } from '@angular/core';

@Injectable()
export class FileService
{
constructor() {}

uploadFile(file): Promise {
return new Promise((resolve, reject) => {
...
}
}
}

然后我将它导入我的 AppModule:

@NgModule({
declarations: [ AppComponent ],
entryComponents: [ AppComponent ],
imports: [ FilesModule ]
})
export class AppModule { }

当我将 FileService 注入(inject)到 AppComponent 时,出现错误:

AppComponent 中的错误:没有文件服务提供者

来自 Angular 文档:

When we import a module, Angular adds the module's service providers (the contents of its providers list) to the application root injector.

This makes the provider visible to every class in the application that knows the provider's lookup token.

我缺少什么来完成这项工作?

最佳答案

当提供者在我的 NgModule 中运行时,我总是创建一个 ForRoot 方法:

@NgModule({
declarations: [FileUploader],
exports: [FileUploader],
imports: [CommonModule]
})
export class FilesModule {

static forRoot(): ModuleWithProviders {
return {
ngModule: FilesModule,
providers: [
FileService
]
}
}
}

然后您可以在您的 AppModule 中使用它:

@NgModule({
declarations: [AppComponent],
entryComponents: [AppComponent],
imports: [FilesModule.forRoot()]
})
export class AppModule {}

关于Angular2 没有服务提供者 - 外部模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com