Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught (in promise): Error: StaticInjectorError(AppModule)[employeService -> Http]:

Tags:

angular

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

Employee service code

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

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

Employee Component code

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 
like image 632
Pardeep Kumar Avatar asked Jun 06 '18 11:06

Pardeep Kumar


1 Answers

You need to import HTTPModule into your main module.

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

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

Update

As per latest versions you should use HttpClientModule instead of HttpModule

Import like this

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

@NgModule({
  declarations: [ ],
  imports: [
    ......
    HttpClientModule
  ]
....
like image 99
Pardeep Jain Avatar answered Nov 11 '22 04:11

Pardeep Jain