【发布时间】:2019-01-08 19:22:49
【问题描述】:
我的回调函数不会调用同一个类实例的另一个成员函数
在 Angular 中使用 typescript,我有一个类,它定义了一个公共成员函数 myCallback(),它作为回调函数传递给 ngrx 商店订阅,并异步调用。 myCallback() 函数尝试调用其同一个类实例的另一个成员函数this.funcA(),但失败并出现funcA() 未定义的错误。
myCallback() 可以调用其同一个类实例的成员属性this.prop,并且可以调用不是同一个类的成员的函数,例如funcB()。
我怀疑这与this 上下文变化有关。但是我可以使用this 成功调用属性,但不能调用函数??
这是怎么回事,我不明白什么?
export class MyClass implements OnInit
{
public prop:boolean;
private sub:Subscriber;
constructor(public storeY:Store<fromY.FeatureState>){}
ngOnInit(){
this.sub = new Subscriber(this.storeY);
this.sub.myCallback = this.myCallback;
this.sub.subscribe();
}
public myCallback()
{
this.prop=true; //works
this.funcA(); //does not work, funcA not defined
funcB(); //works
}
public funcA()
{}
} //end class
funcB(){}
订户类的缩写
export class Subscriber {
public myCallback: () => void;
constructor(public storeY:Store<fromY.FeatureState>)
{ }
public subscribe() //called in external ngOnInit
{
this.storeY.select(state => state.myData)
.pipe()
.subscribe((data:object) =>{
this.myCallback(); //calling callback
}
})
}
【问题讨论】:
-
你试过胖箭头函数吗:myCallback = () => {}
-
因为
this会根据范围而变化,因此 this.funcA() 在您直接从 ngOnInit 调用函数 myCallback 时定义(例如),但在您调用时它将未定义它来自回调中的其他类
标签: angular typescript