在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.
> ES6,CoffeeScript,TypeScript和AtScript都包含a =>将此绑定的运算符.
>您可以使用.bind来使用ES5解决方
>您可以使用Felix上述答案中的一个黑客攻击.

以下是这些示例:

添加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')); 
      }
    });
}];

现在,只有在您第一次访问它时才会延迟加载.

相关文章

AngularJS 是一个JavaScript 框架。它可通过 注:建议把脚本放在 元素的底部。这会提高网页加载速度,因...
angluarjs中页面初始化的时候会出现语法{{}}在页面中问题,也即是页面闪烁问题。出现这个的原因是:由于...
AngularJS 通过被称为指令的新属性来扩展 HTML。AngularJS 指令AngularJS 指令是扩展的 HTML 属性,带有...
AngularJS 使用表达式把数据绑定到 HTML。AngularJS 表达式AngularJS 表达式写在双大括号内:{{ expres...
ng-repeat 指令可以完美的显示表格。在表格中显示数据 {{ x.Name }} {{ x.Country }} 使用 CSS 样式为了...
$http是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。读取 JSON 文件下是存储在web服务器上...