未捕获(承诺):错误:StaticInjectorError(AppModule)[employeService - > Http]:

Par*_*mar 7 angular

当我在我的服务的构造函数中使用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()
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

注意我在员工组件内部直接调用我的服务(不是来自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
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

控制台中的错误消息:

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 
Run Code Online (Sandbox Code Playgroud)

Par*_*ain 17

您需要将HTTPModule导入主模块.

import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [ ],
  imports: [
    ......
    HttpModule
  ]
....
Run Code Online (Sandbox Code Playgroud)

更新

根据最新版本,您应该使用HttpClientModule而不是HttpModule

像这样导入

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

@NgModule({
  declarations: [ ],
  imports: [
    ......
    HttpClientModule
  ]
....
Run Code Online (Sandbox Code Playgroud)