[英]Setting context of “this” from another typescript class, using AngularJS dependency injection
我正在使用TypeScript類在AngularJS中定義一個控制器:
class TrialsCtrl {
constructor(private $scope: ITrialsScope, private ResourceServices: ResourceServices) {
this.loadTrials();
}
loadTrials() {
console.log("TrialsCtrl:", this);
this.Trial.query().then((result) => {
this.$scope.Trials = result;
});
}
remove(Trial: IRestTrial) {
this.ResourceServices.remove(Trial, this.loadTrials);
}
}
angular.module("app").controller("TrialsCtrl", TrialsCtrl);
我正在將常見的控制器方法重構為服務。
class ResourceServices {
public remove(resource, reload) {
if (confirm("Are you sure you want to delete this?")) {
resource.remove().then(() => {
reload();
});
}
}
}
angular.module("app").service("ResourceServices", ResourceServices);
控制台日志顯示,當我希望它為TrialsCtrl
時, this
正在引用窗口上下文。 我的問題是reload()
方法需要在TrialsCtrl
的上下文中TrialsCtrl
,以便它可以訪問this.Trial
和this.$scope
。 如何告訴reload()
方法this
設置為TrialsCtrl
? 還是我應該針對這種事情使用其他解決方法?
你有沒有嘗試過:
this.ResourceServices.remove(Trial, this.loadTrials.bind(this));
要么
this.ResourceServices.remove(Trial, () => this.loadTrials());
對於應該作為回調傳遞的方法(如this.loadTrials
),最好將它們定義為箭頭,
loadTrials = () => { ... }
因此,無論是否使用Function.prototype.bind
它們都保留上下文。
或者,可以在方法上使用裝飾器(例如core-decorators @autobind )來綁定方法,同時仍在類原型上對其進行定義:
@autobind
loadTrials() { ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.