我有一个可观察的订阅,所以当它完成时,我需要它从这个类调用一个函数,问题是" this“关键字指的是订阅,而不是类范围。代码:
export class GoogleMapComponent{
Position:object;
constructor(public MapFunctionsProvider: MapFunctionsProvider) {
let posObservable = this.MapFunctionsProvider.getPosition();
posObservable.subscribe(data =>{
this.Position = data;
this.createMap();// this keyword refers to the subscription
});
function createMap(){
console.log('run')
}
}如何调用createMap()而不声明"this“关键字的新变量?
发布于 2017-07-01 08:14:22
在constructor.because this之外实现引用GoogleMapComponent类的函数
export class GoogleMapComponent {
Position: object;
constructor(public MapFunctionsProvider: MapFunctionsProvider) {
let posObservable = this.MapFunctionsProvider.getPosition();
posObservable.subscribe(data => {
this.Position = data;
this.createMap(); // this keyword refers to the subscription
});
}
createMap(): any {
console.log('run')
}
}发布于 2017-07-01 10:01:38
这与角无关,它是ES6的一个新特性。
当您使用箭头函数()=>()时,this.总是引用类实例,而不管如何嵌套。
如果不想要这种行为,仍然可以使用function(){}。
https://stackoverflow.com/questions/44858770
复制相似问题