在AngularJS的承诺中使用它
是否有最佳实践解决方案能够在承诺中使用?在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 }); } }]; 这个问题有解决方案吗?如何在承诺范围内从我的服务中获取成员或方法? 先感谢您.
回调动态的一般性问题在
in this answer中得到解释,这非常好 – 我不会重复Felix所说的内容.我将讨论承诺特定的解决方案:
Promises是在Promises / A规范下指定的,它允许promise库无缝地使用彼此的promise. Angular $q承诺尊重规范,因此Angular承诺必须按照定义将.then回调作为函数执行 – 即不设置它.在严格模式下执行promise.then(fn)将始终将此值评估为fn内的未定义(以及非严格模式下的窗口). 理由是ES6即将到来,更优雅地解决了这些问题. 那么,你有什么选择? >某些promise库提供.bind方法(例如Bluebird),您可以use these promises inside Angular并换出$q. 以下是这些示例: 添加bind – 又名Promise#bind 假设您已经按照above question and answer进行操作,那么您应该可以: Restangular.one('me').get().bind(this).then(function(response) { this._myVariable = true; // this is correct }); 使用箭头功能 Restangular.one('me').get().then(response => { this._myVariable = true; // this is correct }); 使用.bind Restangular.one('me').get().then(function(response) { this._myVariable = true; // this is correct }.bind(this)); 使用前ES5’黑客’ var that = this; Restangular.one('me').get().then(function(response) { that._myVariable = true; // this is correct }); 当然,还有一个更大的问题 当_myVariable可用时,您当前的设计不包含_know的任何方法.您必须轮询它或依赖内部状态排序.我相信你可以做得更好并且有一个设计,当变量可用时你总是执行代码: app.service('exampleService',function(Restangular) { this._myVariable =Restangular.one('me'); }]; 然后你可以通过this._myVariable.then使用_myVariable(函数(值){.这可能看起来很乏味但是如果你使用$q.all你可以很容易地用几个值来做这个,这在状态同步方面是完全安全的. 如果你想延迟加载它而不是第一次调用它(也就是说,只有在调用myFunction时) – 我完全明白了.你可以使用getter并执行: app.service('exampleService',function(Restangular) { this.__hidden = null; Object.defineProperty(this,"_myVariable",{ get: function(){ return this.__hidden || (this.__hidden = Restangular.one('me')); } }); }]; 现在,只有在您第一次访问它时才会延迟加载. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |