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

时间:2016-08-11 11:45:53

标签: angular

我正在从模拟数据中以表格格式显示数据。即使在组件内部注入服务,也在调用getItems服务方法时获取组件中的错误。任何人都可以帮助我,因为我刚开始学习角度

app.ts

//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 =&gt; 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);          
}

}

2 个答案:

答案 0 :(得分:0)

这不会解决您的问题,但您的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

的代码

答案 1 :(得分:0)

我在getItems之后忘了括号...... !!!!