Angular Promise($ q)不起作用

时间:2013-10-08 12:42:51

标签: javascript angularjs

我正在尝试在我的演示应用程序中使用Angular和SignalR。我正在尝试使用$ q服务来使用promises。不知道我的代码中有什么不对,但它不起作用。

SERVICE

var boardConsole = $.connection.builtinboard;
var chat = angular.module('chat', []);
chat.factory('board', ['$q', '$timeout', function ($q, $timeout) {
var board = {};
board.startBoard = function (callback) {
    $.connection.hub.start(function () {
        if (angular.isFunction(callback)) {
            callback();
        }
    });
};
board.loadAllMessages = function () {
    var deferred = $q.defer();
    boardConsole.server.loadAllMessages().done(function (messages) {
        deferred.resolve(messages);
    }).fail(function () {
        deferred.reject(function () {
            //SHOW NOTHING FOUND 
        });
    });
    return deferred.promise;
};
return board;
} ]);

CONTROLLER

chat.controller('chatController', ['$scope', 'board', function ($scope, board) {
$scope.Messages = [];
board.startBoard(function () {
    board.loadAllMessages().then(function (messages) {
        alert('1');
        $scope.Messages = messages;
    });
});
} ]);

无效

1 个答案:

答案 0 :(得分:1)

将其包裹在$timeout中。如有必要,这将执行安全$apply

$timeout(function(){
    deferred.resolve(messages);
});