更新$无极“这个”上下文属性里面的角JS服务无极、上下文、属性、里面

2023-09-13 02:53:52 作者:誹蕒榀

我有一个函数中定义为我的服务正在使用的:

I have a function being used in my service that is defined as:

var getData = function() {
        return anotherService.getData().$promise;
};

我操纵整个服务这个属性。

this.someProperty = 'a string';

我把我的服务的返回段内的上述功能:

I call the above function inside the return section of my service:

return{
    updateProperty: function(){
        getData().then(function(data){
            this.someProperty = data;
        });
    }
}

在上面,我得到一个这是未定义有关的错误在我的浏览器控制台。我想这是因为解决了$承诺是AJAX调用和这个用于断章取义。什么是操作的最佳途径使用在这种情况下一个AJAX调用返回的数据这属性?

In the above, I get an this is undefined related error in my browser console. I assume this is because the resolved $promise is an AJAX call and this is used out of context. What's the best way to manipulate a this property using the returned data from an AJAX call in this instance?

推荐答案

如果你正在操纵这个整个服务,并将其分配给一个变​​量如 VAR自=此。问题是,这个是一个功能的情况下,可以通过使用其他code fn.call(上下文)或 fn.apply(背景下,参数)。因此它易于为任何给定的功能的范围内不同的

if you're manipulating this throughout your service, assign it to a variable like var self = this. The problem is that this is the context of a function and can be changed by other code using fn.call(context) or fn.apply(context, args). So it's liable to be different inside of the scope of any given function.

因此​​,只要把它分配给了一些变量并使用它:

So just assign it to some variable and use it:

var self = this;

return {
    updateProperty: function(){
        getData().then(function(data){
            self.someProperty = data;
        });
    }
};