我正在使用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
的值。
问题不是由于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);
}
}