未捕获(承诺):错误:StaticInjectorError(AppModule)[employeService-> Http]: [英] Uncaught (in promise): Error: StaticInjectorError(AppModule)[employeService -> Http]:

查看:148
本文介绍了未捕获(承诺):错误:StaticInjectorError(AppModule)[employeService-> Http]:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务的构造函数中使用Http时遇到上述错误.

I am facing above mentioned error when I am using Http inside the constructor of my service.

员工服务代码

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文件)

I am calling the service directly (not from app.module.ts file) inside employee component as

员工组件代码

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
        );
    }
}

我在控制台中看到此错误消息:

And I have this error message in Console :

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 

推荐答案

您需要将HTTPModule导入到您的主模块中.

You need to import HTTPModule into your main module.

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

@NgModule({
  declarations: [ ],
  imports: [
    ......
    HttpModule
  ]
....

更新

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

这样导入

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

@NgModule({
  declarations: [ ],
  imports: [
    ......
    HttpClientModule
  ]
....

这篇关于未捕获(承诺):错误:StaticInjectorError(AppModule)[employeService-&gt; Http]:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆