是否有最佳实践解决方案能够在承诺中使用?在jQuery中,我可以绑定我的对象以在我的promise/callback中使用它 - 但是在angularJS中?有最佳实践解决方案吗?"var service = this;"的方式 我不喜欢......
app.service('exampleService', ['Restangular', function(Restangular) {
this._myVariable = null;
this.myFunction = function() {
Restangular.one('me').get().then(function(response) {
this._myVariable = true; // undefined
});
}
}];
Run Code Online (Sandbox Code Playgroud)
这个问题有解决方案吗?如何在承诺范围内从我的服务中获取成员或方法?
先感谢您.
Ben*_*aum 21
回答中动态的一般问题在这个答案中this得到了解释,这个问题非常好 - 我不会重复Felix所说的内容.我将讨论承诺特定的解决方案:
Promise在Promises/A +规范下指定,允许promise库无缝地使用彼此的promise.Angular $ q承诺尊重规范,因此Angular承诺必须按照定义将.then回调作为函数执行- 即没有设置this.在严格模式下,执行promise.then(fn)将始终评估this为未定义的内部fn(以及window非严格模式).
理由是ES6即将到来,更优雅地解决了这些问题.
那么,你有什么选择?
.bind方法(例如Bluebird),你可以在Angular中使用这些promise并换掉$ q.=>绑定的运算符this..bind以下是这些示例:
Promise#bind假设您已按照上述问题回答,您应该可以:
Restangular.one('me').get().bind(this).then(function(response) {
this._myVariable = true; // this is correct
});
Run Code Online (Sandbox Code Playgroud)
Restangular.one('me').get().then(response => {
this._myVariable = true; // this is correct
});
Run Code Online (Sandbox Code Playgroud)
.bindRestangular.one('me').get().then(function(response) {
this._myVariable = true; // this is correct
}.bind(this));
Run Code Online (Sandbox Code Playgroud)
var that = this;
Restangular.one('me').get().then(function(response) {
that._myVariable = true; // this is correct
});
Run Code Online (Sandbox Code Playgroud)
您当前的设计在_myVariable可用时不包含任何_know的方法.您必须轮询它或依赖内部状态排序.我相信你可以做得更好,并且有一个设计,当变量可用时你总是执行代码:
app.service('exampleService', ['Restangular', function(Restangular) {
this._myVariable =Restangular.one('me');
}];
Run Code Online (Sandbox Code Playgroud)
然后你可以使用_myVariablevia this._myVariable.then(function(value){.这可能看起来很乏味但是如果你使用$q.all它可以很容易地用几个值来做这个,这在状态同步方面是完全安全的.
如果你想延迟加载它而不是第一次调用它(也就是说,只有当myFunction被调用时) - 我完全得到它.您可以使用getter并执行:
app.service('exampleService', ['Restangular', function(Restangular) {
this.__hidden = null;
Object.defineProperty(this,"_myVariable", {
get: function(){
return this.__hidden || (this.__hidden = Restangular.one('me'));
}
});
}];
Run Code Online (Sandbox Code Playgroud)
现在,只有在您第一次访问它时才会延迟加载.
| 归档时间: |
|
| 查看次数: |
5013 次 |
| 最近记录: |