6

我已经拿起了一个项目,我正在尝试将一些数据从服务返回到我的控制器。我已经在这里待了大约 12 个小时,并尝试了不同的方法。它们通常都会导致这种“缺失数据”。

我试过了

  • 使用 $resource 而不是 $http
  • $http.get在不使用承诺的情况下将权利放在控制器内
  • 服务作为实际服务(而不是工厂),没有回报
  • 建立工厂一堆不同的方式来返回各种格式的数据
  • 使用 setTimeout 和 $apply

我觉得我现在拥有的东西很简单,而且我读过的所有内容都说这应该可行

angularjs-load-data-from-service

角度控制器无法从服务中获取数据

angularjs-promises-not-firing-when-returned-from-a-service

angularjs-promise-not-resolving-properly

angularjs-promise

这些链接是从今天开始的。

我认为可能存在 $scope 问题,因为过去我看到 $scopes 在使用多个控制器时无法获取数据,但是该站点只是在index.html中声明了一个控制器作为<body ng-app="myApp" ng-controller="BodyCtrl">设置。主要的app.js使用状态(我相信来自 ui-router)......

.state('app.view', {
    url: '/view',
    templateUrl: 'views/view.tpl.html',
    controller: 'MyCtrl'
   })

将控制器附加到不同的页面。此外,该站点还有一些其他控制器从服务中获取数据,我首先将其作为模板查看,但是,那里的数据和返回比我想要得到的要复杂得多。不过,最重要的是,控制器正在访问服务提供的数据。他们都在使用 $resource,这就是我从这个问题开始的方式。我一直坚持使用 $http,因为它应该可以工作,而且我想在我进入“更高级别”之前让它与它一起工作。另外,我只需要从端点获取,所以觉得 $resource 有点矫枉过正。

服务

.factory('MyService', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope) {
    var defer = $q.defer();
    var factory = {};
    factory.all = function () {
        $http({method: 'GET', url: 'http://URLtoJSONEndpoint'}).
            success(function (data, status, headers, config) {
                console.log('data success', data);
                defer.resolve(data);
            }).
            error(function (data, status, headers, config) {
                console.log('data error');
                defer.reject(data);
            });

        return defer.promise;
    };
    return factory;
}]);

控制器

.controller('MyCtrl', ['$scope', '$state', '$stateParams', '$rootScope', 'MyService', '$q', function ($scope, $state, $stateParams, $rootScope, MyService, $q) { 
...
...
$scope.data = null;
$scope.object = MyService;
$scope.promise = MyService.all();

MyService.all().then(function (data) {
    $scope.data = data;
    console.log("data in promise", $scope.data);
})
console.log("data", $scope.data);
console.log("object", $scope.object);
console.log("promise", $scope.promise);

$http({method: 'GET', url: 'http://URL'}).
        success(function (data, status, headers, config) {
            $scope.data = data;
            console.log('data success in ctrl', data);
        }).
        error(function (data, status, headers, config) {
            console.log('data error');
        });

    console.log("data after ctrl", $scope.data);


    angular.forEach($scope.data, function (item) {
        // stuff that I need $scope.data for
    }

控制台日志

所以这是我的控制台日志,我可以得到这么多,只是不是实际数据!这就是我需要的。我什至发疯了,并扩展了我.then(function (data) {的功能以捕获控制器中需要的所有功能$scope.data。那是火车残骸。

***data null***
object Object {all: function}
promise Object {then: function, catch: function, finally: function}
***data success after ctrl null***
data success in ctrl Array[143]
data success Array[143]
data in promise Array[143]
data success Array[143]

据我所知,这应该可行,但我不确定问题可能出在哪里!也许我不明白 Promise 是如何工作或解决的。我之前在另一个项目中使用过 Angular,但我一开始就在那里,并且了解它是如何组合在一起的。这个项目的结构不同,感觉更加混乱。我想简化它,但我什至似乎无法获得一些简单的数据来返回!

感谢您在确定为什么这不起作用时提供的任何帮助/反馈,谢谢!

编辑:所以问题是,为什么会console.log("data", $scope.data)在承诺之前返回 null/?

在控制器再往下一点我有这个

angular.forEach($scope.data, function (item) {
// stuff
}

它似乎无权访问数据。

EDIT2:我添加了$http.get我在控制器内部使用的,以及它的控制台日志和我需要的实际$scope.dataforEach

编辑3:

更新服务

.service('MyService', ['$http', function ($http) {
    function all() {
        return $http({
            url: 'http://URL',
            method: 'GET'
        });
    }

    return {
        all: all
    }
}]);

更新的控制器

MyService.all().success(function (data) {
        $scope.data = data;

        angular.forEach($scope.data, function (item) {

            // Turn date value into timestamp, which is needed by NVD3 for mapping dates
            var visitDate = new Date(item.testDate).getTime();

            switch (item.Class) {
                case "TEST":
                    testData.push(
                        [
                            visitDate,
                            item.Total
                        ]
                    );

            }

        });

        console.log("test Data in success", testData);
    });


$scope.testData = [
        {
            "key": "Test",
            "values": testData
        }
    ];

所以$scope.testData需要在视图中使用(nvd3图表),它没有获取数据。

解决方案

MyService.all().success(function (data) {
        $scope.data = data;

        angular.forEach($scope.data, function (item) {

            // Turn date value into timestamp, which is needed by NVD3 for mapping dates
            var visitDate = new Date(item.testDate).getTime();

            switch (item.Class) {
                case "TEST":
                    testData.push(
                        [
                            visitDate,
                            item.Total
                        ]
                    );
            }

        });

        console.log("test Data in success", testData);

        $scope.testData = [
        {
            "key": "Test",
            "values": testData
        }
    ];
    });
4

2 回答 2

5

这可能是一个非常简单的示例,说明您的服务可能如下所示:

app.service('MyService', ['$http', function ($http) {
  function all() {
    return $http({
      url: 'data.json',
      method: 'GET'
    });
  }

  return {
    all: all
  }
}]);

在控制器中,您可以像这样使用它:

app.controller('AppCtrl', ['$scope', 'MyService', function ($scope, MyService) {
  $scope.data = null;

  MyService.all().success(function (data) {
    $scope.data = data;

    // init further handling of `.data` here.
  });
}]);

演示http ://plnkr.co/edit/l8pF8Uaa312A8kPtaCNM?p=preview


回答为什么控制台记录的问题data null:这仅仅是因为日志发生在异步调用完成之前。

于 2014-05-07T14:58:36.370 回答
0

我面临同样的问题。我通过$rootScope在 promise 内部使用而不是$scope.So $rootScope.datawill beavailable 来解决这个问题console.log

于 2015-12-03T09:38:36.253 回答