AngularJS工厂第一次不返回数据,但在调用interval方法后返回

AngularJS工厂第一次不返回数据,但在调用interval方法后返回,angularjs,multidimensional-array,angularjs-scope,Angularjs,Multidimensional Array,Angularjs Scope,我正在尝试创建一个AngularJS工厂,为我的应用程序提供一个企业列表。但我似乎无法在第一次运行时获取变量。但是在运行interval之后,我得到了变量 我在第一次运行页面中的控制器时得到: angular.js:12783错误:[$injector:undef]提供程序“businessList”必须从$get factory方法返回一个值 但我认为我的解决方案是错误的,怎么可能呢?有人能给我指一下正确的方向吗?例如,在这里使用rootScope是一个好主意吗 我想要的是在我的应用程序中有一

我正在尝试创建一个AngularJS工厂,为我的应用程序提供一个企业列表。但我似乎无法在第一次运行时获取变量。但是在运行interval之后,我得到了变量

我在第一次运行页面中的控制器时得到:

angular.js:12783错误:[$injector:undef]提供程序“businessList”必须从$get factory方法返回一个值

但我认为我的解决方案是错误的,怎么可能呢?有人能给我指一下正确的方向吗?例如,在这里使用rootScope是一个好主意吗

我想要的是在我的应用程序中有一个全球可访问的企业列表,该列表在访问开始时收集,并用计时器自我更新。所以我不必一直从laravel后端调用工业请求,当我可以在列表中找到它时。。这是我的主意

工厂:

myApp.factory('businessList', ['$interval', '$http', '$rootScope',
    function($interval, $http, $rootScope) {
      function bedriftliste() {
        $http.get('get/allebedrifter')
            .then(function(result) {
                bedrifter = result.data;
                $rootScope.bedrifter = bedrifter;
            });
        return $rootScope.bedrifter;
    }
    var bedrifter = bedriftliste();
    // start periodic checking
    $interval(bedriftliste, 5000);
    return bedrifter;
}
]);
控制器

myApp.controller('bsC', ['$rootScope', '$scope', 'businessList', 
                    function($rootScope, $scope, businessList) {
    $scope.allebedrifter = businessList;
}]);`

我通过在对象为null时执行http.get来解决这个问题

        if (!$rootScope.allebedrifter) { 
        $http.get('get/bedrift/' + $scope.tslug)
            .then(function(result) {
                bedriften = result.data;
                $scope.bedriften = bedriften;
       });  

这样似乎很好

虽然我指出得晚了,但这似乎不是解决这个问题的正确方法。您需要在factory中进行以下更改:

myApp.factory('businessList', ['$interval', '$http', '$rootScope',
function($interval, $http, $rootScope) {
  function bedriftliste() {
    return $http.get('get/allebedrifter');
}
} ]);

在控制器中,您将执行以下操作:

myApp.controller('bsC', ['$rootScope', '$scope', 'businessList', function($rootScope, $scope, businessList) {
                    function TestFunction(){
     businessList.bedriftliste().then(function successCallback(response) {
        $scope.allebedrifter = response.data;
//it will invoke 5 seconds after you receive the response from your factory method, I didn't test it but it will solve your problem
        $interval(TestFunction, 5000);
    }, function errorCallback(response) { 
    });
}            

}]))

它第一次抛出错误的原因,因为$rootScope.bedrifter在第一次加载工厂时未定义。它只有在解析$http响应后才有值;那当然不行。在我提供任何答案之前,我能知道您是否有其他使用$http的工作服务吗?如果是,为什么要以这种方式编写此服务?只是为了确保您了解$http和承诺。