我有一些测试代码(Testing.ts),其中包含以下代码段:
let injector = ReflectiveInjector.resolveAndCreate([
TestService
])
var myInstance = new myTest(injector.get(TestService));
TestService.ts具有以下代码:
@Injectable()
export class TestService {
protected basePath = '/test/ ';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
}
我使用tsc
将Testing.ts编译为testing.js并运行node testing.js
运行代码,我收到错误消息:Error: No provider for HttpClient! (TestService -> HttpClient)
。在TestService中,我有:
import {
HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent
} from '@angular/common/http';
在api.module.ts中,我有:
import { HttpClientModule } from '@angular/common/http';
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from
'@angular/core';
import { CommonModule } from '@angular/common';
import { Configuration } from './configuration';
import { TestService } from './api/test.service';
@NgModule({
imports: [ BrowserModule, CommonModule,
HttpClientModule ],
declarations: [],
exports: [],
providers: [
TestService ]
})
在Testing.ts中,我有:import { TestService } from '../api/api';
根据我对使用import语句的此项目结构的了解,注入器应该没有问题为TestService的构造函数创建HttpClient实例。在Windows上运行angular ^ 4.3.0。我想念什么吗?所有帮助将不胜感激!
答案 0 :(得分:0)
要解决此问题,HttpClient是Angular通过HTTP与远程服务器通信的机制。
要使HttpClient在应用程序中的任何地方都可用,
打开根AppModule, 从@ angular / common / http导入HttpClientModule符号, 将其添加到@ NgModule.imports数组。 将以下内容添加到app.module.ts:
从'@ angular / common / http'导入{HttpClientModule}; 之后,在import部分中添加import:[HttpClientModule,]
此过程在文档中进行了说明