什么是引用角封闭的内部服务属性/方法最合适的方法是什么? [英] What's the most appropriate way to reference a service property/method inside a closure in Angular?

查看:84
本文介绍了什么是引用角封闭的内部服务属性/方法最合适的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造一个角度的服务,我想最好的做法是什么下面的场景。

I'm creating an Angular service, and I wondered what the best practice is for the scenario below.

authModule.service('authService', 
    function($http, $sessionStorage, $window, $q, $rootScope) {

        this.variable1 = true;

        this.processVariable = function () {
            return $http({...}).then(function(response) {
            variable1 = response.data; 
            //line above this will throw an error because it's not scoped

        }, function (reason) {

        });
    }
} 

如果我用淘汰赛,我想补充 VAR自我=这一点; 上方变量1 声明,然后使用 self.variable1 而不是变量1

If I were using Knockout, I'd add var self = this; above the variable1 declaration and then use self.variable1 instead of variable1.

时使用无功自我=这一点; 的最佳做法,还是有不同的preferred方法采用了棱角分明的时候?

Is the use of var self = this; the optimal practice, or is there a different preferred approach when using Angular?

推荐答案

您可以只把它定义为一个变量

You could just define it as a variable

 var variable1 = true;

如果您想将其设置为实例属性 this.variable1 = TRUE;

if you want to set it as instance property this.variable1 = true;

那么你可以做: -

then you could do:-

      var _that = this; 
      this.processVariable = function () {
        return $http({...}).then(function(response) {
        _that.variable1 = response.data; 
        //line above this will throw an error because it's not scoped

    }, function (reason) {

    });

原因是这个当你的回调内不会作用域服务实例 $ HTTP 答应。您还可以使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\"相对=nofollow>绑定改变内回调的背景下有其作用范围是服务实例。

Reason is the this will not be scoped to the instance of your service when you are inside the callback of $http promise. You can also use bind to change the context inside the callback to have it scoped to the service instance.

但是,当呼叫连续做可能会有问题(因为服务是单这将是相同的 this.variable1 您将被修改或重写任何电话回来最后一个),不知道到底是什么你正在尝试做的,但最好的事情是从服务承诺回调返回的数据。

But there could be issues when the call is made consecutively (and because service is a singleton it will be the same this.variable1 you will be modifying or overwriting whichever call comes back last), not sure what exactly you are trying to do,but best thing would be to return the data from the promise callback in the service.

authModule.service('authService', 
    function($http, $sessionStorage, $window, $q, $rootScope) {
      this.processVariable = function () {
        return $http({...}).then(function(response) {
            return response.data; 
            //line above this will throw an error because it's not scoped
        }, function (reason) {
            $q.reject(reason)
        });
    }
} 

这篇关于什么是引用角封闭的内部服务属性/方法最合适的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆