首页 文章

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

提问于
浏览
0

我正在从模拟数据中以表格格式显示数据 . 即使在组件内部注入服务,也在调用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 => 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

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

  • 0

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

相关问题