javascript - Factory 有两种方法,一种是 $http 方法和 $promise - 如何从第一个方法的成功函数中引用另一种方法?

标签 javascript angularjs angularjs-service angularjs-controller angular-services

在我的一个工厂中,我需要在获取数据时设置一个变量(通过 $http),这样我就可以在我的 Controller 中访问它(目的是显示一个微调图像直到数据已加载)。

.factory('LoadData', function LoadData($http, $q){
    return {

        getMyData: function(){
            return $http(
                // implementation of the call
            ).then(
                function(response){
                    var myData = response.data;

                    // this should be reference to the other method (getLoadStatus) 
                    // where I want to change its value to "true"

                    // this doesn't work - "this" or "self" don't work either because we're in another function
                    LoadData.getLoadStatus.status = true;
                }
            );
        },
        // by calling the below method from my controller,
        // I want to mark the completion of data fetching
        getLoadStatus = function(){

            var status = null;

            return status;

        }
    }
}

我希望您明白了 - 如何实现?此外,我愿意接受任何旨在改进方法的建议(我想尽可能采用最佳实践)。

最佳答案

Status本质上是一个私有(private)变量;用作:

.factory('LoadData', function LoadData($http, $q){
    var status = null; // ESSENTIALLY PRIVATE TO THE SERVICE
    return {
        getMyData: function(){
            return $http(...).then(function(response){
                ...
                status = true;
            });
        },
        getLoadStatus = function(){
            return status;
        }
    };
})

关于javascript - Factory 有两种方法,一种是 $http 方法和 $promise - 如何从第一个方法的成功函数中引用另一种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26223114/

相关文章:

javascript - 状态如何传递到react-redux应用程序中的选择器?

charts - 可以通过拖动点来编辑图形的图表库?

javascript - Chrome 更新 61.0.3163.79 CPU 使用率高

javascript - 在 ng-change 之后从 Controller 重置 ng-model 值

javascript - Angular 1.2 $q 在同一函数中多次返回 $q.promise(不同条件)时中断

Angular : Using common service in different modules

javascript - 通过 google app engine channel api 发送数据 uri

javascript - 无法将表达式与输入值绑定(bind)

javascript - 使用匿名函数和 $q promise 时的 AngularJS 'this' 问题

javascript - Angular Js $注入(inject)器:unpr error