如何将变量值赋值给AngularJS函数是否使变量未定义?

时间:2015-11-19 01:43:52

标签: javascript angularjs

这是我的主控制器:

angular.module("HomePageApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {

        var self = this;

        self.posts = BaseService.fetch['YPosts']();
        self.logoutUser = function() {
            console.log(self.posts);
            BaseService.logout();
        };

    }]);

这是我的BaseService(为简单起见,未显示某些返回对象):

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var cerrorMessages = [];
        var posts = {};
        return {

        fetch: {
            XPosts: function() {
                $http.get('/postsX/')
                .then(function(response) {
                    posts = response.data;
                }, function(response) {
                    posts = {};
                    cerrorMessages = BaseService.accessErrors(response.data);
                });
                return posts;
            },

            YPosts: function() {
                $http.get('/postsY')
                .then(function(response) {
                    posts = response.data;
                    console.log(posts);
                    return posts;
                }, function(response) {
                    console.log('here');
                    posts = {};
                    cerrorMessages = BaseService.accessErrors(response.data);
                });
            }
        }
    };
}]);

当我在posts中记录BaseService时,它由对象组成。但是当我点击logout(再次记录posts)时,它表示未定义。知道为什么吗?

2 个答案:

答案 0 :(得分:1)

then()中的YPosts是一个Promise回调,返回的值与从YPosts返回值不同。您在XPosts中执行的操作也不起作用:您return posts本身XPosts,但该值尚未设置,因为在大多数情况下,$http.get赢了还没有调用then / success回调。

你可以在lyjackal的回答中引入另一个回调,或者只是在正确的位置使用现有回调:

       YPosts: function() {
            return $http.get('/postsY')
       }

    var self = this;
    BaseService.fetch.YPosts().then(
        function(response) { self.posts = response.data; },
        function(response) { ... } // error handler
    );

    self.logoutUser = function() {
        console.log(self.posts);
        BaseService.logout();
    };

请注意,如果在logoutUser完成之前调用YPosts函数,console.log(self.posts)将再次显示undefined

答案 1 :(得分:1)

return语句仅从其函数范围返回。 Javascript倾向于鼓励将回调传递给长时间运行的函数,以便代码不会阻止其他活动。如果您希望解决获取请求后的帖子值,请YPosts进行回调:

        YPosts: function(callback) {
            $http.get('/postsY')
            .then(function(response) {
                posts = response.data;
                console.log(posts);
                callback(posts);
            }, function(response) {
                console.log('here');
                posts = {};
                cerrorMessages = BaseService.accessErrors(response.data);
            });
        }

修改

像这样打电话给YPosts:

BaseService.fetch.YPosts(function(posts) {
    self.posts = posts;
});
// however note that the callback will not be executed until the request completes
// so `self.posts === undefined` out here