【发布时间】:2019-11-23 23:24:15
【问题描述】:
为了将 Angular 5 项目迁移到 Angular 8,我使用 Angular CLI 创建了一个空项目,并将我的模块、组件和服务复制到我的新项目结构中。 该项目已构建,但在执行时我收到了经典消息“服务中没有 HttpClient 的提供者”:
ERROR NullInjectorError: StaticInjectorError(AppModule)[TimeService -> HttpClient]:
StaticInjectorError(Platform: core)[TimeService -> HttpClient]:
NullInjectorError: No provider for HttpClient!
at NullInjector.get (http://localhost:4200/vendor.js:50573:27)
at resolveToken (http://localhost:4200/vendor.js:52359:24)
at tryResolveToken (http://localhost:4200/vendor.js:52285:16)
at StaticInjector.get (http://localhost:4200/vendor.js:52148:20)
at resolveToken (http://localhost:4200/vendor.js:52359:24)
at tryResolveToken (http://localhost:4200/vendor.js:52285:16)
at StaticInjector.get (http://localhost:4200/vendor.js:52148:20)
at resolveNgModuleDep (http://localhost:4200/vendor.js:76198:29)
at _createClass (http://localhost:4200/vendor.js:76275:32)
at _createProviderInstance (http://localhost:4200/vendor.js:76231:26)
我的 app.module.ts 没问题:我正在导入 HttpClientModule 并将其放入 @NgModule 导入中,就在 BrowserModule 之后。
@NgModule({
declarations: [AppComponent,DelegationsComponent],
imports: [BrowserModule,
HttpClientModule,
GlobalModule.forRoot(),
AuthenticationModule,
DelegationModule,
routing,
FormsModule,
ReactiveFormsModule,
BrowserAnimationsModule,
ButtonModule, TableModule, DialogModule, DropdownModule, ToastModule, TabViewModule, InputTextModule, AutoCompleteModule, TooltipModule, CheckboxModule, OverlayPanelModule, MultiSelectModule, CalendarModule ],
providers: [APP_ROUTER_PROVIDERS, {provide: APP_BASE_HREF, useValue: getBaseHref()}],
bootstrap: [AppComponent]
})
错误似乎在 TimeService 中。在该服务中,HttpClient 被导入并注入到构造函数中。
import {HttpClient} from "@angular/common/http";
@Injectable()
export class TimeService extends BaseService {
constructor(private http: HttpClient)
然后,TimeService 被注入到DelegationsComponent 中。
import {TimeService} from "utils/time.service";
@Component({
moduleId: __moduleName,
selector: 'delegations',
templateUrl: './delegations.component.html'
})
export class DelegationsComponent implements OnInit, OnDestroy {
constructor(private timeService: TimeService)
你可以在我的 app.module.ts 声明中看到DelegationsComponent。
有什么想法吗? 谢谢
编辑: 通过尝试在一个小示例中重现该问题,我找到了原因:time.service.ts 不在我的 Angular 应用程序中,而是在外部的文件夹中,因为我正在与其他两个 Angular 应用程序共享它。感谢我的应用程序的 package.json,我将其包括在内:
"utils": "file:../../../../../utils"
所以 time.service.ts 以 node_modules/utils 结束。如果我把它放在 src/app 目录中,它就可以工作。知道为什么它不能以这种方式工作,以及如何在多个 Angular 应用程序之间共享服务吗?
【问题讨论】:
-
检查 import { HttpClientModule } from '@angular/common/http';
-
我已经在 app.module.ts 中了。其他地方需要吗?
标签: angular8