【问题标题】:Angularjs: PromisesAngularjs:承诺
【发布时间】:2013-08-21 01:09:05
【问题描述】:

我正在做一些小练习来学习 AngularJS,目前试图了解如何使用 Promise。

在下面的练习中,我试图让一些数据异步。我可以在 console.log 中看到数据,但是 promise 返回 NULL。

  • GET /entries 200 OK
  • 承诺已解决:null

任何有经验的人都可以给我一些建议,以了解我做错了什么?感谢收看!

angular.module('questions', [])

.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        controller: 'MainCtrl',
        resolve: {
            'MyServiceData': function(EntriesService) {
                return EntriesService.promise;
            }
        }
    })
})

.service('EntriesService', function($http) {

    var entries = null;

    var promise = $http.get('entries').success(function (data) {
        entries = data;
    });

    return {
        promise: promise,
        all: function() {
            return entries;
        }
    };
})

.controller('MainCtrl', ['$scope', 'EntriesService', function($scope, EntriesService) {

  console.log('Promise is resolved: ' + EntriesService.all());

  $scope.title = "Q&A Module";

  $scope.entries = EntriesService.all() || [];

  $scope.addMessage = function() {
    $scope.entries.push({
        author: "myAuthor",
        message: $scope.message
    });
  };

}]);

/******感谢大家迄今为止的帮助** ***/

在听取了@bibs 的建议后,我想出了以下解决方案,使用 ngResource 很清楚:

angular.module('questions', ['ngResource'])

.factory('EntriesService', function($resource){
  return $resource('/entries', {});
})

.controller('MainCtrl', ['$scope', 'EntriesService', function($scope, EntriesService) {

  $scope.title = "Q&A Module";

  $scope.entries = [];

  EntriesService.query(function(response){
    $scope.entries = response;        
  });

  $scope.addMessage = function() {
    $scope.entries.push({
        author: "myAuthor",
        message: $scope.message
    });
  };

}]);

【问题讨论】:

  • 你想达到什么目的?在您登录 EntriesService.all() 时,您的承诺似乎尚未解决,因此该值仍然为空。
  • 坦克寻找@bibs!我想在调用 mainCtrl 的任何时候异步获取一些数据,所以在这种情况下,我想知道“EntriesService”如何在我 console.log() 时获得可用的数据!我还在学习,所以我认为,通过创建“服务”并使用 promise 这将返回数据。很明显,我并没有完全理解 Promise,因此,当我初始化它时,数据在 ctrl 中不可用。应该怎么写正确?

标签: javascript angularjs promise


【解决方案1】:

您应该访问回调中的数据。由于entries 可能在数据到达之前为空,因此all() 函数在这种情况下并不是很有用。

试试这个,你应该可以将then()方法链接到同步获取数据。

.service('EntriesService', function ($http) {
    var services = {
        all: function () {
            var promise = $http.get('entries').success(function (data) {
                entries = data;
            }).error(function (response, status, headers, config) {
                //error
            });
            return promise;
        },

        someOtherServices: function(){
            var promise = ....
            return promise;
        }

        return services;
    }
});

$scope.entries = [];
EntriesService.all().then(function(data){
    $scope.entries = data;
});

【讨论】:

  • 嗨,sza,非常感谢您的帮助!我想,对于学习这一点的人来说是可以的,但这是正确的做法吗? *不是你的解决方案,而是我写的
  • @heldrida 没问题,让我更新我的答案以显示一些与 http 调用相关的可扩展模式。
【解决方案2】:

如果您希望服务器返回的数据立即反映在您的视图中:

.service('EntriesService', function($http) {

    var entries = [];

    var promise = $http.get('entries').success(function (data) {
        for (var i = 0; i < data.length; i++) {
            entries[i] = data[i];
        }
    });

    return {
        promise: promise,
        all: entries
    };
})

.controller('MainCtrl', ['$scope', 'EntriesService', function($scope, EntriesService) {

  $scope.title = "Q&A Module";

  $scope.entries = EntriesService.all;

  $scope.addMessage = function() {
    $scope.entries.push({
        author: "myAuthor",
        message: $scope.message
    });
  };

您可能需要查看$resource 为您执行此操作:http://docs.angularjs.org/api/ngResource.$resource

【讨论】:

  • 非常感谢您关注@bibs!这是有效的,它真的帮助我开始理解 Promise 是如何工作的。我将阅读有关 $resource 的内容并做一些练习并尝试提出一个可行的解决方案。谢谢!
猜你喜欢
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 2013-10-29
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多