我已经创建了一个实现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'
允许我动态添加属性 - 我做错了什么?
答案 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);
}