繁体   English   中英

TypeError:不是[null]中的函数,在angular2中调用服务方法时在组件中获取此错误

[英]TypeError: is not a function in [null] getting this error in component while calling method of service in angular2

我从模拟数据中以表格格式显示数据。 即使将服务注入组件内部,在调用服务的getItems方法时也会出现组件错误。 我刚刚开始学习角度知识,有人可以帮我吗

应用程序

//our root app component
import {Component, OnInit, Provide} from 'angular2/core'
import {ItemController} from './ItemController';
import {ItemControllerService} from './ItemController.service';



@Component({
  selector: 'my-app',
  providers: [ItemControllerService] ,


  template: `
    <div>
    <table border=1 ng-controller="ItemController">

      <th>Id</th>
      <th>Location</th>
      <th>Event</th>
      <th>Benefit Name</th>
      <th>Inactive from date</th>


    <tbody *ngFor="#item of items">
        <tr>
            <td>{{item.id}}</td>
            <td>{{item.location}}</td>
            <td>{{item.event}}</td>
            <td>{{item.benefit}}</td>
            <td>{{item.inactivedate}}</td>
        </tr>
        </tbody>
    </table>


    </div>
  `,
  directives: []
})
export class App {
  items: ItemController[];
   constructor(private service: ItemControllerService){}



  getitems(){

    this.service.getItems().then(items=>this.items = items);

  }

  ngOnInit(){
    this.getitems();
  }
}

错误处在this.service.getItems()。then(items => this.items = items); ItemControllerService

import {Item} from './ItemController';
import {Injectable,Inject} from 'angular2/core';
import {ITEMS} from './mock-items';
import {ItemController} from './ItemController';



@Injectable()
export class ItemControllerService{


   getItems{
  return Promise.resolve(ITEMS);          
}

}

这不会解决您的问题,但是您的template存在问题。 它看起来应该像这样:

<table border=1>
  <tbody>
    <tr>
      <th>Id</th>
      <th>Location</th>
      <th>Event</th>
      <th>Benefit Name</th>
      <th>Inactive from date</th>
    </tr>
    <tr *ngFor="#item of items">
      <td>{{item.id}}</td>
      <td>{{item.location}}</td>
      <td>{{item.event}}</td>
      <td>{{item.benefit}}</td>
      <td>{{item.inactivedate}}</td>
    </tr>
  </tbody>
</table>

修复html,您不需要ng-controller

请同时提供ItemController代码

我忘记了getItems之后的括号... !!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM