javascript - Angularjs: promise

标签 javascript angularjs promise

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

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

  • 获取/条目 200 确定
  • Promise 已解决: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
    });
  };

}]);

最佳答案

您应该访问回调中的数据。由于在数据到达之前 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;
});

关于javascript - Angularjs: promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18339792/

相关文章:

javascript - 返回 promise 的函数的串行执行

javascript - Promise 在 Node module.exports 中返回未定义

javascript - 使用 Angular 时 HTML 表格中的行总和不正确

javascript - 编辑textContent或innerHTML会杀死eventListener

javascript - 如何在 Javascript 中推送代理对象中的数组值

javascript - 设置 div 背景颜色的 Angular 指令

AngularJS:如何观看选项卡选择?

c# - 在 Chrome 缓存中调试 MVC2 项目过于激进

javascript - 预渲染 io 给出 404 错误

javascript - Promise - `then()` 未按预期工作