Angular 2给出" TypeError:emitter.subscribe不是函数"

时间:2015-12-21 18:22:08

标签: angular

我使用angular 2创建了一个小应用程序,我在我的应用程序中创建了2个组件调用app.component.ts和sidkik.component.ts我尝试将sidkik.component.ts导入到app.component.ts和在app.component中使用sidkik的sidkik标签,它在控制台中给出了以下错误。请帮我解决这个问题。

erorr

angular2.dev.js:23524 EXCEPTION: TypeError: emitter.subscribe is not a function in [heroes in AppComponent@3:6]

app.component.js

import {Component} from 'angular2/core';
import {SideKikComponent} from './classes/sidekik.component';

interface Hero {
 id: number;
 name: string;
 sidekik:string;
}

@Component({
  selector: 'my-app',
  templateUrl:'app/views/heros.html',
  directives: [SideKikComponent],
  styleUrls: ['app/css/site.css']
})

export class AppComponent { 
  public title = 'Tour of Heroes';
  public heroes =HEROS;
  public selectedHero: Hero;

  onSelect(hero: Hero) { 
    this.selectedHero = hero; 
  }
}

var HEROS: Hero[] =[
    {"id":1,"name":"SuperMan","sidekik":"one"},
    {"id":2,"name":"Captain America","sidekik":"two"},
    {"id":3,"name":"Thor","sidekik":"three"},
    {"id":4,"name":"Iorn Man","sidekik":"four"},
    {"id":5,"name":"Ant Man","sidekik":"five"}
];

sidkik.component.ts

import {Component} from 'angular2/core';

@Component({
  selector:'sidekik',
  events:['hit'],
  properties:['define'],
  template: `
    <sidekik (click) = "hit(define)"></sidekik>
  `,

 })

 export class SideKikComponent{
    hit(define:string){
    console.log(define);
  }
}

1 个答案:

答案 0 :(得分:2)

错误是由您定义组件的方式引起的。特别是events: ['hit'], Angular期望这是组件中的EventEmitter实例,它将从其他组件可以订阅的SidekikComponent实例中触发事件。您定义为hit的是一个将在点击事件中调用的函数。

正如其他人已经指出您在提供的代码段中存在其他问题,例如template:不应包含其中组件的选择器。