【问题标题】:angular library with service missing HttpClient缺少服务的 Angular 库 HttpClient
【发布时间】:2020-02-22 01:59:34
【问题描述】:

我已经创建了共享 Angular 8 库,该库带有负责进行 http 调用以获取一些数据的服务。库很好,当我导入我的模块时,我遇到了错误

我已经添加,所以服务将被添加到 root。

@Injectable({
  providedIn: 'root'
})

我已经在 AppModule 中导入了服务 另外,导入 HttpClientModule

库中的MyServiceProvider

@Injectable({
  providedIn: 'root'
})

export class MyServiceProvider {

  private endpointUrl: string;

  constructor(
    private http: HttpClient,
    private proxy: ProxyService) {

    this.endpointUrl = this.proxy.getEndpoint();
  }

  getMydata() {

    return this.http.post(this.endpointUrl).pipe(
      map(response => {
        console.log(response);
      })
      , catchError((error: HttpErrorResponse) => {
        return throwError(error.error);
      }));
  }

}

在 AppModule 中


import { MyServiceProvider } from 'my-lib';


@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    IonicStorageModule.forRoot()
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    MyServiceProvider ---> (also tried without this)
  ],
  bootstrap: [AppComponent]
 })
 export class AppModule { }

错误错误:未捕获(承诺):NullInjectorError:StaticInjectorError(AppModule)[MyServiceProvider -> HttpClient]: StaticInjectorError(Platform: core)[MyServiceProvider -> HttpClient]:

【问题讨论】:

  • 您找到解决方案了吗?我面临着同样的问题,即使我将 HttpClientModule 导入到我的根 AppModule 中,DI 也不向库服务提供 HttpClient。 (角度 10)
  • 你有 my-service-provider.module.ts 文件吗?如果是,我认为您需要在那里导入 HttpClientModule。

标签: angular angular-ui-router angular7


【解决方案1】:

您应该将 HttpModule 导入到您的模块中。

import { HttpModule } from '@angular/http';

@NgModule({
    imports: [
        HttpModule
    ]
    ...
})

【讨论】:

  • 我使用的是 Angular 8.1.2。 HttpModule 已弃用。而是使用 HttpClientModule。
猜你喜欢
  • 2018-05-09
  • 2019-02-25
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2016-09-22
相关资源
最近更新 更多