2017-10-04 96 views
14

我開始與CLI的一個新的角度項目,並運行到HttpClient錯誤沒有提供商。Angular 4錯誤:沒有供應商爲HttpClient

我已將HttpClientModule添加到我的模塊導入中,這似乎是此場景中常見的罪魁禍首。除此之外,網上找不到很多,所以我不確定問題可能是什麼。

我app.module.ts

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

和我的服務

@Injectable() 
export class FlexSearchService { 


    constructor(private http: HttpClient) {} 

    getSavedSearchResult(index: string, queryName: string, query: string): Observable<any> { 
     const url = `${environment.flexUrl}/${index}/search`; 
     const item = new SearchQuery({queryName: queryName, variables: {q: query}}); 
     return this.http.post(url, item); 
    } 
} 

和NG版提供了以下輸出

@angular/cli: 1.4.2 
node: 6.9.4 
os: darwin x64 
@angular/animations: 4.4.4 
@angular/common: 4.4.4 
@angular/compiler: 4.4.4 
@angular/core: 4.4.4 
@angular/forms: 4.4.4 
@angular/http: 4.4.4 
@angular/platform-browser: 4.4.4 
@angular/platform-browser-dynamic: 4.4.4 
@angular/router: 4.4.4 
@angular/cli: 1.4.2 
@angular/compiler-cli: 4.4.4 
@angular/language-service: 4.4.4 
typescript: 2.3.4 

我tsconfig

{ 
    "compileOnSave": false, 
    "compilerOptions": { 
    "outDir": "./dist/out-tsc", 
    "sourceMap": true, 
    "declaration": false, 
    "moduleResolution": "node", 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "target": "es5", 
    "typeRoots": [ 
     "node_modules/@types" 
    ], 
    "lib": [ 
     "es2017", 
     "dom" 
    ] 
    } 
} 

我的測試

import { TestBed, inject } from '@angular/core/testing'; 
import { HttpClientModule } from '@angular/common/http'; 
import { FlexSearchService } from './flex-search.service'; 

describe('FlexSearchService',() => { 
    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     providers: [FlexSearchService, HttpClientModule] 
    }); 
    }); 
    it('should be created', inject([FlexSearchService], (service: FlexSearchService) => { 
    expect(service).toBeTruthy(); 
    })); 

任何幫助,不勝感激!

+0

你能發佈確切的錯誤信息嗎? – yurzui

+0

並請添加您的tsconfig.json – yurzui

+1

您在哪裏提供FlexSearchService? – yurzui

回答

17

在您的測試

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

應該

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

非常感謝你! – mrpotocnik

2

更簡單的方法是在全球範圍內提供它....導入到下列app.module.ts像這樣:

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

並聲明它在進口:

imports: [ 
    HttpModule, 
    HttpClientModule, ... 
] 
相關問題