0

I am doing angular quick start tutorial. So I am just Hero tutorial that specifies in angular2 quickstart on its website. That runs fine for me. it binds static array data and perform CRUD. But now I want to learn how to call web API method for getting data from database.

So I am calling webapi method in getHeroes() method of service and calling that method from init method-ngOnInit() of component but it gives error like this. please correct if I am wrong.

Got this error, while calling Web api controller from my service in angular2

EXCEPTION:

Error: Uncaught (in promise): No provider for Http! (DashboardComponent -> HeroService -> Http)BrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23925 STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23925 Error: Uncaught (in promise): No provider for Http! (DashboardComponent -> HeroService -> Http)
    at resolvePromise (angular2-polyfills.js:602)
    at angular2-polyfills.js:579
    at ZoneDelegate.invoke (angular2-polyfills.js:390)
    at Object.NgZoneImpl.inner.inner.fork.onInvoke (angular2.dev.js:2126)
    at ZoneDelegate.invoke (angular2-polyfills.js:389)
    at Zone.run (angular2-polyfills.js:283)
    at angular2-polyfills.js:635
    at ZoneDelegate.invokeTask (angular2-polyfills.js:423)
    at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (angular2.dev.js:2118)
    at ZoneDelegate.invokeTask (angular2-polyfills.js:422)BrowserDomAdapter.logError @ angular2.dev.js:23925
angular2-polyfills.js:528 Unhandled Promise rejection: No provider for Http! (DashboardComponent -> HeroService -> Http) ; Zone: angular ; Task: Promise.then ; Value: NoProviderErrorconsoleError @ angular2-polyfills.js:528
angular2-polyfills.js:530 Error: Uncaught (in promise): No provider for Http! (DashboardComponent -> HeroService -> Http)(…)consoleError @ angular2-polyfills.js:530

Here is my Hero service:

    import {Injectable} from 'angular2/core';
    import {Http,Response,Headers} from 'angular2/http';
    import 'rxjs/add/operator/map'
    import {Observable} from 'rxjs/Observable';
    import {Hero} from '/Scripts/FirstEx_Ts/Hero.ts';
    import {HEROES} from '/Scripts/FirstEx_Ts/MockHeros.ts';


    @Injectable()
   export class HeroService {



   private headers: Headers;

    constructor(private _http:Http) {
   }

 getHeroes(){

  return      this._http.get("http://localhost:54046/api/Heromanage/GetAllHeroes")
       .map((response: Response) => <Hero[]>response.json())
       .catch(this.handleError);
 }
 getHeroesSlowly() {
   return new Promise<Hero[]>(resolve =>
       setTimeout(() => resolve(HEROES), 2000) // 2 seconds
       );
 }

 getHero(id: number) {
   return Promise.resolve(HEROES).then(
       heroes => heroes.filter(hero => hero.id === id)[0]
       );
}

  private handleError(error: Response) {
   console.error(error);
   return Observable.throw(error.json().error || 'Server error');
 }
 } 

And here is my Component from where I am calling service method:

import {Component, OnInit} from 'angular2/core';
import {Http,Response,Headers} from 'angular2/http';
import { CORE_DIRECTIVES } from 'angular2/common';
import {Router} from 'angular2/router';
import {Hero} from '/Scripts/FirstEx_Ts/Hero.ts';
import {HeroService} from '/Scripts/FirstEx_Ts/HeroService.ts';

@Component({
selector: 'my-dashboard',
providers: [HeroService],
templateUrl: '/Templates/DashboardComponent.html',
directives: [CORE_DIRECTIVES],
styles: [ `
[class*='col-'] {
 float: left;
}
*, *:after, *:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
 }
h3 {
 text-align: center; margin-bottom: 0;
 }
[class*='col-'] {
 padding-right: 20px;
 padding-bottom: 20px;
 }
  [class*='col-']:last-of-type {
  padding-right: 0;
  }
  .grid {
  margin: 0;
   }
  .col-1-4 {
   width: 25%;
  }
   .module {
    padding: 20px;
   text-align: center;
   color: #eee;
  max-height: 120px;
  min-width: 120px;
  background-color: #607D8B;
  border-radius: 2px;
    }
 h4 {
   position: relative;
  }
  .module:hover {
    background-color: #EEE;
    cursor: pointer;
      color: #607d8b;
  }
 .grid-pad {
   padding: 10px 0;
  }
  .grid-pad > [class*='col-']:last-of-type {
   padding-right: 20px;
   }
 @media (max-width: 600px) {
.module {
  font-size: 10px;
  max-height: 75px; }
  }
   @media (max-width: 1024px) {
  .grid {
  margin: 0;
    }
   .module {
  min-width: 60px;
   }
   }
 `]
  })
 export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(
    private _router: Router,
    private _heroService: HeroService) {
debugger;

}
**ngOnInit() {
    alert('hi');
    debugger;
     this._heroService
        .getHeroes()
        .subscribe((heroes:Hero[]) => this.heroes = data,
            error => console.log(error),
            () => console.log('Get all Items complete'));
}**
gotoDetail(hero: Hero) {
    let link = ['HeroDetail', { id: hero.id }];
    this._router.navigate(link);
  }

  }
1
  • what version of angular you are using, you have not added provider for HTTP. if anything gretaer than RC5 import HttpModule. Commented Sep 22, 2016 at 13:02

1 Answer 1

0

you may try below,

Angular version < RC5

include HTTP_PROVIDERS in the providers array of Component metadata.

Angular version >= RC5

import HttpModule in the Module containing your component.

Hope this helps!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.