angular - subscribe 中的 Angular 2 "this"关键字如何引用该类?

标签 angular typescript observable

我有一个可观察的订阅,所以当它完成时我需要它从这个类调用一个函数,问题是“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')

    }
}

如何在不声明“this”关键字的新变量的情况下调用 createMap() ?

最佳答案

在构造函数外部实现该函数。因为 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')

    }
}

关于angular - subscribe 中的 Angular 2 "this"关键字如何引用该类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858770/

相关文章:

android - Retrofit 接口(interface)中 Call 和 Observable Response 的区别

angular - 将 routerLink 与来自 angular2 中的 Promise 的参数一起使用

共享模块中的 Angular 导入/导出模块或多个模块中的导入

angular - VSCode/tslint 不解析 tsconfig.json 中的路径

html - 从数组值更改 Css

javascript - 将 switchMap 与 Promises 结合使用

angular - 如何从主题中获取最后一个值?

node.js - Angular 中的模板解析警告

angularjs - 为什么 TypeScript 在实现接口(interface)时允许将返回类型重载为 'any'

angular - 以编程方式禁用响应式(Reactive)表单组件