Angular 4 Error: No provider for HttpClient

后端 未结 5 1345
北恋
北恋 2020-12-25 09:40

I am starting a new angular project with the CLI and am running into a no provider for HttpClient error.

I have added HttpClientModule to m

相关标签:
5条回答
  • 2020-12-25 10:22

    An easier way is to provide it globally....Import the following into app.module.ts like so:

    import { HttpModule } from '@angular/http'
    import { HttpClient, HttpClientModule } from '@angular/common/http';
    

    and declare it in imports:

      imports: [
        HttpModule,
        HttpClientModule, ...
    ]
    
    0 讨论(0)
  • 2020-12-25 10:27

    In your test

    TestBed.configureTestingModule({
          providers: [FlexSearchService, HttpClientModule]
        });
    

    It should be

    TestBed.configureTestingModule({
          imports: [HttpClientModule],
          providers: [FlexSearchService]
        });
    

    or even better (if you want to mock request):

    TestBed.configureTestingModule({
          imports: [HttpClientTestingModule],
          providers: [FlexSearchService]
        });
    
    0 讨论(0)
  • 2020-12-25 10:34

    Import HttpClientTestingModule.

    In your test:

    import { HttpClientTestingModule } from '@angular/common/http/testing';
    

    and in the configureTestingModule of your test, do the following:

    TestBed.configureTestingModule({
        imports: [ HttpClientTestingModule ],
    })
    .compileComponents();
    
    0 讨论(0)
  • 2020-12-25 10:34

    I've noticed this issue when I was trying to link my angular library locally within my project using the npm link.

    Downloading the library from the repository solved my issue.

    0 讨论(0)
  • 2020-12-25 10:42

    For this you have to import the following:

    import { HttpClientTestingModule } from '@angular/common/http/testing';
    

    And for the spec file in the configureTestingModule of your test, do the following:

    TestBed.configureTestingModule({
        imports: [ HttpClientTestingModule ],
    })
    .compileComponents();
    
    0 讨论(0)
提交回复
热议问题