【发布时间】:2015-12-02 10:48:01
【问题描述】:
目前有点与此作斗争,因为我不明白为什么会这样。我会告诉你控制器。
class ExampleClassController {
constructor($scope, serviceItem, PrepService, consts) {
// Services
this.serviceItem = serviceItem;
// Init Values
this.grid = PrepService;
this.dates = [
moment().format('x'),
moment().add(14, 'days').format('x')
];
// Works fine
console.log(this._init());
// Events
$scope.$on(consts.events.change, this._init);
}
_init() {
// this.grid = {};
// Returns null
console.log(this, "in the init");
return this.serviceItem.get().then((res) => this.grid = res);
}
}
这是奇怪的部分,当我在构造函数中调用 this._init 时,它很好。按照建议返回承诺。但是当我在 $scope.$on 事件中调用它时,它就会崩溃并说这是空的。我似乎无法弄清楚它为什么会发生,因为它似乎没有发生在其他任何人的例子中。任何事情都会有所帮助,只是了解为什么会很棒。
谢谢!
【问题讨论】:
-
您在使用回调时丢失了对
this的引用。你可以在$scope.$on中做this._init.bind(this) -
你是怎么知道在
_init中使用箭头函数的?.then((res) => this.grid = res);- 将相同的逻辑应用于您的constructor
标签: javascript angularjs ecmascript-6