简体   繁体   English

AngularJS服务返回未定义

[英]AngularJS Service returns undefined

I have the following service: 我有以下服务:

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

}];

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 var,以便可以在前端显示。

$scope.message is undefined $scope.message未定义

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

Your function getMessage has no return statement. 您的函数getMessage没有return语句。 But $http is asynchronous so it will return a promises . 但是$ 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;
        }
    };

}];

And in your controller 而在您的控制器中

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

If you want to clean your response in emailService you need to declare a promises by yourself. 如果要在emailService中清除响应,则需要自己声明一个Promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM