物业' createGame $'在游戏服务'上不存在

时间:2016-10-17 16:05:41

标签: angular typescript

我已经创建了一个实现GameService的{​​{1}}类:

ServiceInterface

export interface ServiceInterface { emitter$; actions: any[]; [action: string]: any; } export class GameService implements ServiceInterface { constructor() { super(); this.actions = [ { name: 'createGame$', handler: this.createGame.bind(this) } ]; this.registerActions(); } registerActions() { // for each action, create action subject and subscribe a handler if (this.actions) { for (let action of this.actions) { this[action.name] = new Subject(); this[action.name].subscribe(action.handler); } } } 动态添加属性,在本例中为GameService。但是我收到了错误:

this.createGame$

我认为界面上的Property 'createGame$' does not exist on 'GameService' 允许我动态添加属性 - 我做错了什么?

1 个答案:

答案 0 :(得分:0)

在您创建actions时,您尝试将createGame绑定到尚不存在的操作

this.actions = [
    { name: 'createGame$', handler: this.createGame.bind(this) }
];

我会在registerActions中创建处理程序,因为此时您可以引用当前action

 constructor(){
    this.actions = [
        {name:'createGame$', handler:null}
     ];
     this.registerActions();
 }

 registerActions(){
    //current class instance. includes createGame$ property
    console.log('registerActions(): ', this); 

     if(this.actions){
        for (let action of this.actions) {
            //set handler here instead of constructor in order to bind
            // to current action
            action.handler = this.createGame.bind(action); 

             this[action.name] = new Subject();
             this[action.name].subscribe(action.handler);
         }
     }
 }

 createGame(){
    // here, 'this' is the current action
    console.log('createGame(): ', this);
 }

plunker demo