当我在服务的构造函数中使用Http时,我面临上述错误。
员工服务代码
import {Component} from '@angular/core'
import {Injectable} from '@angular/core'
import { HttpModule } from '@angular/http';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/observable';
import 'rxjs/add/operator/map';
@Injectable()
export class employeService{
constructor(public http : Http){
}
getEmployeename() : Observable<string>{
return
this.http.get('http://localhost:53656/api/values/Getdata').map((resp:
Response) => resp.json());
}
}
注意我在员工组件内直接调用我的服务(不是来自app.module.ts文件)
员工组件代码
import { Component, OnInit} from '@angular/core';
import {employeService} from './Service/service';
@Component({
templateUrl: './app.employee.html',
providers: [ employeService ]
})
export class EmployeeComponent implements OnInit{
empName : string;
constructor(private empService : employeService){
}
ngOnInit(){
this.empService.getEmployeename().subscribe((empName)=>this.empName =
empName);
}
}
控制台中的错误消息:
core.js:1598 ERROR Error: Uncaught (in promise): Error:
StaticInjectorError(AppModule)[employeService -> Http]:
StaticInjectorError(Platform: core)[employeService -> Http]:
NullInjectorError: No provider for Http!
Error: StaticInjectorError(AppModule)[employeService -> Http]:
StaticInjectorError(Platform: core)[employeService -> Http]:
NullInjectorError: No provider for Http!
at
答案 0 :(得分:8)
您需要将HTTPModule导入主模块。
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [ ],
imports: [
......
HttpModule
]
....
根据最新版本,您应使用HttpClientModule
代替HttpModule
像这样导入
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [ ],
imports: [
......
HttpClientModule
]
....
答案 1 :(得分:0)
在app.module.ts中 你应该使用HttpClientModule 还将您的服务提供商导入提供商