AngularJS Service返回undefined [英] AngularJS Service returns undefined

查看:189
本文介绍了AngularJS Service返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下服务:

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;
            });
        }
    };

}];

在我的控制器中,我将返回值分配给 $ scope.message var以便我可以在前端显示。

In my controller I am assigning the return value to a $scope.message var so that I can display in the front end.

$ scope.message 未定义

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


推荐答案

你的函数getMessage没有回报声明。但 $ http 是异步的,所以它会返回承诺

Your function getMessage has no return statement. But $http is asynchronous so it will return a 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中清理你的回复,你需要声明一个承诺你自己。

If you want to clean your response in emailService you need to declare a promises by yourself.

这篇关于AngularJS Service返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆