AngularJS Service returns undefined

心不动则不痛 提交于 2019-12-01 07:37:43

问题


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 is undefined

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

回答1:


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

}];

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.



来源:https://stackoverflow.com/questions/31099630/angularjs-service-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!