Angular 4错误:没有供应商为HttpClient
问题描述:
我开始与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();
}));
任何帮助,不胜感激!
答
在您的测试
TestBed.configureTestingModule({
providers: [FlexSearchService, HttpClientModule]
});
应该
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [FlexSearchService]
});
+2
非常感谢你! – mrpotocnik
答
更简单的方法是在全球范围内提供它....导入到下列app.module.ts像这样:
import { HttpModule } from '@angular/http'
import { HttpClient, HttpClientModule } from '@angular/common/http';
并声明它在进口:
imports: [
HttpModule,
HttpClientModule, ...
]
你能发布确切的错误信息吗? – yurzui
并请添加您的tsconfig.json – yurzui
您在哪里提供FlexSearchService? – yurzui