【问题标题】:Angular 7. NullInjectorError: No provider for HttpClient! Even when app.module has HttpClientModule. How to fix it?Angular 7. NullInjectorError:没有 HttpClient 的提供者!即使 app.module 有 HttpClientModule。如何解决?
【发布时间】:2019-04-12 08:14:29
【问题描述】:

我正在使用 Angular 7,并且我正在尝试使用一项服务,该服务使用 HttpClient 在我的 .Net Core MVC 应用程序中从我的 APIController 调用 API 链接。每当我在输入 ng test 后尝试在 cmd 窗口中进行测试时,它都会给我一个错误,并且它仅适用于我要修复的服务:

ProductService should be created
Error: StaticInjectorError(DynamicTestModule)[HttpClient]: 
  StaticInjectorError(Platform: core)[HttpClient]: 
    NullInjectorError: No provider for HttpClient!

以下是我在以下文件中编写代码的方式:

product.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Product } from '../product';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  productsUrl = "api/ProductsAPI";

  constructor(private http: HttpClient) { }

  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(this.productsUrl)
      .pipe(
        catchError(this.handleError<Product[]>('getProducts'))
      );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      //// TODO: better job of transforming error for user consumption
      //this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}

product.service 文件中有 HttpClient,我读到它不起作用,除非 HttpClientModule 在 app.module 文件的 import 部分,并且 product.service 类在 providers 部分。

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { ProductsComponent } from './products/products.component';

import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { ProductService } from './products/product.service';

@NgModule({
  declarations: [
    AppComponent,
    ProductsComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [ProductService],
  bootstrap: [AppComponent]
})
export class AppModule { }

它仍然给我一个“没有 HttpClientModule 的提供者”错误。我想使用 product.service,并将其导入另一个组件。

有人对如何解决这个问题有任何建议或答案吗?

【问题讨论】:

  • 你能复制粘贴'ng --version'的输出并分享你的spec文件的代码吗?如果您启动 ng serveng build,一切正常?
  • 在我的模块中使用 import HttpClientModule 时出现类似的错误,因此我更改为 HttpClient 并且一切正常。你能试试吗

标签: angular model-view-controller .net-core asp.net-core-mvc


【解决方案1】:

我有办法消除 nullInjetorError 问题。我以为我必须将 HttpClientModule 类放在 product.service 文件的 app.module.ts 文件的导入部分中,但事实证明我必须将它导入到 spec 文件的导入部分中,product.service 文件。 service.spec.ts.

product.service.spec.ts

describe('ProductService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    declarations: [ProductsComponent],
    imports: [HttpClientModule]
  })
  );

当 product.component 中仍然存在该问题时,我将 HttpClientModule 类添加到 product.component.spec.ts 文件的导入部分,m 并解决了问题。

product.component.spec.ts

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProductsComponent],
      imports: [HttpClientModule]
    })
    .compileComponents();
  }));

我不需要将 HttpClientModule 类添加到 app.module.ts 的导入部分,我只需要将它添加到规范文件的导入部分,这就解决了我的“NullInjectorError: No”问题HttpClient 的提供者。问题。

希望对遇到同样问题的人有所帮助。

【讨论】:

    【解决方案2】:

    我认为您收到了来自app.component.spec.ts 的错误。您还必须导入必要的组件和模块进行测试,试试这个:


    app.component.spec.ts

    ...
    TestBed.configureTestingModule({
      declarations: [ your_component ],
      imports: [ your_module ],
      providers: [ your_service ]
    }).compileComponents();
    

    【讨论】:

    • 好的,按照你的建议试试。我运行了 ng test 命令,得到的错误不止一个。我删除了,这是由于在导入部分添加了“AppModule”引起的。
    猜你喜欢
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2020-06-04
    • 2022-01-03
    • 2023-03-10
    相关资源
    最近更新 更多