Home » Javascript » No provider for Http while HttpModule is imported

No provider for Http while HttpModule is imported

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a project that come from an angular 4 bootstrap 4 template.

I got the famous Error: No provider for Http while using a custom service that need it to do request to a custom API :

import {Http, Response} from "@angular/http";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";
import {Config} from "../../../webapp/src/config";
import {HttpModule} from "@angular/http";

/**
 * Created by Sorikairo on 4/24/2017.
 */

@Injectable()
export class ApiService {
    public isLoggedIn: boolean = false;
    public token: string = null;

    constructor(public http: Http, public config: Config) {

    }

    public loginUser(user) {
        return this.http.post(this.config.apiUrl + "login/user", {user: user}).map(this.extractData)
            .catch(this.handleError);
    }

    public createUser(user) {
        return this.http.post(this.config.apiUrl + "user", {user: user}).map(this.extractData)
            .catch(this.handleError);
    }

    public createProduct(product)
    {
        return this.http.post(this.config.apiUrl + "product", {product: product}).map(this.extractData)
            .catch(this.handleError);
    }

    public modifyProduct(product)
    {
        return this.http.put(this.config.apiUrl + "product", {product: product}).map(this.extractData)
            .catch(this.handleError);
    }



    public extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    public handleError(error: Response | any) {
        // In a real world app, you might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        return Observable.throw(error.json());
    }

    public IsLoggedIn() {
        return this.isLoggedIn;
    }

    public setToken(token) {
        this.token = token;
    }

    public setStatus(status) {
        this.isLoggedIn = status;
    }
}

However, HttpModule is imported in my app.module.ts :

import { BrowserModule} from '@angular/platform-browser';
import { BrowserAnimationsModule} from "@angular/platform-browser/animations";
import { HttpModule, Http } from '@angular/http';
import { RouterModule } from '@angular/router';
import { NgModule} from '@angular/core';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';

import { MaterialModule} from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { AgmCoreModule } from '@agm/core';
import { TourNgBootstrapModule } from 'ngx-tour-ng-bootstrap';
import { NgxDatatableModule } from "@swimlane/ngx-datatable";


import { PerfectScrollbarModule, PerfectScrollbarConfigInterface } from "ngx-perfect-scrollbar";
import { TranslateModule, TranslateLoader, TranslateStaticLoader } from 'ng2-translate/ng2-translate';
import { SidebarModule } from 'ng-sidebar';
import 'hammerjs';

import { ChankyaAppComponent} from './app.component';
import { AppRoutes } from "./app-routing.module";
import { MainComponent }   from './main/main.component';
import { HorizontalLayoutComponent } from './horizontal-layout/horizontal-layout.component';
import { MenuToggleModule } from './core/menu/menu-toggle.module';
import { MenuItems } from './core/menu/menu-items/menu-items';
import { PageTitleService } from './core/page-title/page-title.service';
import {LoginoneComponent} from "./login/loginone.component";
import {FilterTableComponent} from "./table/table-filter.component";
import {DashboardRoutes} from "./dashboard/dashboard.routing";
import {DirectivesModule} from "./core/directive/directives.module";
import {NgxChartsModule} from "@swimlane/ngx-charts";
import {CommonModule} from "@angular/common";
import {DashboardComponent} from "./dashboard/dashboard-v1/dashboard.component";
import {UserListComponent} from "./user-pages/user-list/userlist.component";
import {ProductListComponent} from "./product-pages/product-list/productlist.component";
import {CompanyListComponent} from "./company-pages/product-list/companylist.component";
import {ProductDetailComponent} from "./product-pages/product-detail/productdetail.component";
import {RouterOutletComponent} from "./router-outlet.component";
import {ApiService} from "../../../webapp/src/app/api.service";

export function createTranslateLoader(http: Http) {
  return new TranslateStaticLoader(http, 'assets/i18n', '.json');
}

const perfectScrollbarConfig: PerfectScrollbarConfigInterface = {
  suppressScrollX: true
};

@NgModule({
    imports: [
        HttpModule,
        BrowserModule,
        BrowserAnimationsModule,
        FormsModule,
        ReactiveFormsModule,
        MaterialModule,
        SidebarModule.forRoot(),
        RouterModule.forRoot(AppRoutes),
        TourNgBootstrapModule.forRoot(),
        FlexLayoutModule,
        NgbModalModule.forRoot(),
        AgmCoreModule.forRoot({apiKey: 'AIzaSyBtdO5k6CRntAMJCF-H5uZjTCoSGX95cdk'}),
        PerfectScrollbarModule.forRoot(perfectScrollbarConfig),
        MenuToggleModule,
        CommonModule,
        FormsModule,
        NgxChartsModule,
        DirectivesModule,
        RouterModule.forChild(DashboardRoutes),
        NgxDatatableModule,
        TranslateModule.forRoot({
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [Http]
        }),
    ],
    declarations: [
        ChankyaAppComponent,
        MainComponent,
        LoginoneComponent,
        HorizontalLayoutComponent,
        FilterTableComponent,
        DashboardComponent,
        UserListComponent,
        ProductListComponent,
        CompanyListComponent,
        ProductDetailComponent,
        RouterOutletComponent
    ],
    entryComponents: [
    ],
    bootstrap: [ChankyaAppComponent],
    providers:[
        MenuItems,
        PageTitleService,
        ApiService
    ]
})
export class ChankyaAppModule { }

My dependencies are up-to-date or at least support NgModule:

  "dependencies": {
    "@agm/core": "1.0.0-beta.0",
    "@angular/animations": "4.3.2",
    "@angular/common": "4.3.2",
    "@angular/compiler": "4.3.2",
    "@angular/core": "4.3.2",
    "@angular/flex-layout": "2.0.0-beta.8",
    "@angular/forms": "4.3.2",
    "@angular/http": "4.3.2",
    "@angular/material": "2.0.0-beta.7",
    "@angular/platform-browser": "4.3.2",
    "@angular/platform-browser-dynamic": "4.3.2",
    "@angular/router": "4.3.2",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5",
    "@swimlane/ngx-charts": "5.3.1",
    "@swimlane/ngx-datatable": "9.3.0",
    "angular-calendar": "0.19.0",
    "angular-resizable-element": "^1.2.0",
    "angular-sortablejs": "^2.0.6",
    "angular-tree-component": "3.8.0",
    "chart.js": "2.6.0",
    "ckeditor": "4.6.0",
    "classlist.js": "^1.1.20150312",
    "core-js": "2.4.1",
    "d3": "^4.9.1",
    "dragula": "3.7.2",
    "easy-pie-chart": "2.1.7",
    "font-awesome": "4.7.0",
    "hammerjs": "2.0.8",
    "intl": "^1.2.4",
    "jquery": "2.2.4",
    "jqvmap": "^1.5.1",
    "leaflet": "^1.0.2",
    "leaflet-map": "0.2.1",
    "moment": "^2.15.0",
    "ng-sidebar": "^6.0.0",
    "ng2-ace-editor": "^0.2.3",
    "ng2-archwizard": "^1.7.0",
    "ng2-breadcrumb": "0.5.14",
    "ng2-charts": "1.6.0",
    "ng2-ckeditor": "1.1.9",
    "ng2-dnd": "^4.2.0",
    "ng2-drag-drop": "^2.5.0",
    "ng2-dragula": "1.5.0",
    "ng2-file-upload": "1.2.1",
    "ng2-google-charts": "^3.0.1",
    "ng2-translate": "5.0.0",
    "ng2-tree": "^2.0.0-alpha.10",
    "ng2-validation": "4.2.0",
    "ng2modules-easypiechart": "^0.0.4",
    "ngx-mydatepicker": "2.0.12",
    "ngx-perfect-scrollbar": "^2.0.1",
    "ngx-quill": "^1.3.1",
    "ngx-toastr": "^5.3.0",
    "ngx-tour-ng-bootstrap": "^1.0.6",
    "normalize.css": "^5.0.0",
    "nvd3": "^1.8.5",
    "perfect-scrollbar": "^0.6.16",
    "popper.js": "^1.12.5",
    "quill": "^1.2.3",
    "rxjs": "5.4.2",
    "tether": "1.4.0",
    "screenfull": "^3.2.2",
    "simple-line-icons": "^2.4.1",
    "skycons": "^1.0.0",
    "sortablejs": "^1.6.0",
    "summernote": "^0.8.4",
    "ts-helpers": "^1.1.2",
    "web-animations-js": "^2.3.1",
    "widgster": "0.0.3",
    "zone.js": "^0.8.16"
  },
  "devDependencies": {
    "@angular/cli": "1.3.2",
    "@angular/compiler-cli": "4.3.2",
    "@types/d3": "^3.5.17",
    "@types/jasmine": "2.5.52",
    "@types/jquery": "3.2.0",
    "@types/node": "7.0.8",
    "@types/nvd3": "^1.8.33",
    "codelyzer": "3.0.1",
    "jasmine-core": "2.6.3",
    "jasmine-spec-reporter": "4.1.0",
    "karma": "1.7.0",
    "karma-chrome-launcher": "2.1.1",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "1.3.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "protractor": "5.1.2",
    "ts-node": "3.0.6",
    "tslint": "5.4.3",
    "typescript": "2.3.4"
  }
}

I have other project created with angular cli that do not fail to provide Http, only this one has a problem, but I cannot find why…

Answers:

Your error seems to be coming whether from one of the npm dependencies or from the services you are injecting in your providers.

You can try to see if there is no circular dependency in your services or if there is a service you are not injecting in you providers.