AngularJS Service返回undefined

时间:2015-06-28 12:10:05

标签: javascript angularjs angularjs-service angularjs-controller

我有以下服务:

m1 <- m[order(m[,1]),]

combs <- combn(nrow(m1), 2, function(ind, mat) mat[ind, ], mat = m1)
combs[,, apply(combs, 3, function(mat) mat[2,2] > mat[1,2])]

在我的控制器中,我将返回值分配给app.services.emailService = ['$http', '$sce', function ($http, $sce) { return { getMessage: function(messageId, callback) { $http.get('/api/email/inbox' + '/' + messageId).then(function(response) { response.data.message.updated_at = new Date(response.data.message.updated_at.replace(/-/g,"/")); response.data.message.body = $sce.trustAsHtml(response.data.message.body); return response.data; }); } }; }]; var,以便我可以在前端显示。

$scope.message未定义

$scope.message

1 个答案:

答案 0 :(得分:3)

你的函数getMessage没有return语句。但$http是异步的,因此会返回promises

app.services.emailService = ['$http', '$sce', function ($http, $sce) {

    return {
        getMessage: function(messageId, callback) {
            var deferred = $q.defer();
            $http
                .get('/api/email/inbox' + '/' + messageId)
                .then(function () {
                    response.data.message.updated_at = new Date(response.data.message.updated_at.replace(/-/g,"/"));
                    response.data.message.body = $sce.trustAsHtml(response.data.message.body);
                    deferred.resolve(response.data);
                })
                .catch(function (e) {
                    deferred.reject(e);
                );
            return deferred.promise;
        }
    };

}];

在您的控制器中

$scope.getMessage = function(messageId) {
    emailService
        .getMessage($scope.messages[messageId].id)
        .then(function (message) {
            $scope.message = message;
            console.log(message);
        });
}

如果您想在emailService中清理您的回复,您需要自己申报承诺。