使用胖箭头语法*和*声明返回类型的Angular / TypeScript方法的语法是什么?

问题描述 投票:0回答:1

我正在使用Angular 6.在下面的简化代码中,我有一个名为getActive()的方法。在那个方法中,我想访问this.active的值,但是this对象不在范围内。

如何对此应用胖箭头语法,以便在方法内可以访问this.active的值?我已经浏览了网页并尝试了我能想到的所有可能的语法,但它们都没有编译。

export class PlayerComponent implements OnInit {

  active: boolean;   
  isActive: Observable<boolean> = this.getActive();

  constructor() {
      this.active = false;
  }

  getActive(): Observable<boolean> {
      return of(this.active);
  }

}

请注意,当我在getActive()方法中手动设置返回值时,我的应用程序运行正常,例如:return of(false);只是它无法访问this.active的值。

angular typescript angularjs-scope
1个回答
1
投票

问题不是由于this或箭头函数的绑定,而是由于初始化的顺序。首先调用字段初始化程序(因此调用getActive方法),然后才执行构造函数的其余部分。你可以在生成的es5代码中看到这个:

var PlayerComponent = /** @class */ (function () {
    function PlayerComponent() {
        this.isActive = this.getActive(); // active not set yet
        this.active = false;
    }
    PlayerComponent.prototype.getActive = function () {
        return of(this.active);
    };
    return PlayerComponent;
}());

最简单的解决方案是在构造函数中移动observable的初始化,您可以在其中控制顺序:

export class PlayerComponent implements OnInit {

    active: boolean;
    isActive: Observable<boolean>;

    constructor() {
        this.active = false;
        this.isActive = this.getActive();
    }

    getActive(): Observable<boolean> {
        return of(this.active);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.