【问题标题】:Issue while calling web api controller from service in angular2从 angular2 中的服务调用 Web api 控制器时出现问题
【发布时间】:2016-09-22 12:23:38
【问题描述】:

我正在做 Angular 快速入门教程。 所以我只是在其网站上的 angular2 quickstart 中指定的英雄教程。 这对我来说很好。它绑定静态数组数据并执行 CRUD。 但是现在我想学习如何调用 Web API 方法从数据库中获取数据。

所以我在getHeroes() 服务方法中调用 webapi 方法,并从组件的 init method-ngOnInit() 调用该方法,但它给出了这样的错误。 如有错误请指正。

在 angular2 中从我的服务调用 Web api 控制器时遇到此错误

例外:

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

这是我的英雄服务:

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

这是我调用服务方法的组件:

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

  }

【问题讨论】:

  • 您使用的是什么版本的 Angular,您尚未添加 HTTP 提供程序。如果有任何比 RC5 更重要的内容,请导入 HttpModule

标签: asp.net-web-api angular


【解决方案1】:

你可以试试下面,

Angular 版本

在组件元数据的 providers 数组中包含 HTTP_PROVIDERS

Angular 版本 >= RC5

在包含您的组件的模块中导入HttpModule

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-18
    • 2018-03-08
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多