Javascript 为什么将变量的值赋给AngularJS函数会导致变量未定义?

Javascript 为什么将变量的值赋给AngularJS函数会导致变量未定义?,javascript,angularjs,Javascript,Angularjs,这是我的主控制器: angular.module("HomePageApp", ["BaseApp"]) .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) { var self = this; self.posts = BaseService.fetch['YPosts'](); self.l

这是我的主控制器:

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(为了简单起见,没有显示一些返回对象):

当我在我的
BaseService
中记录
posts
时,它由对象组成。但是,当我单击“注销”(再次记录“发布”)时,它表示它未定义。知道为什么吗?

您的
YPosts
中的
then()
是一个承诺回调,在那里返回值与从
YPosts
返回值不同。在
XPosts
中执行的操作也不起作用:您
XPosts
中返回posts
,但该值尚未设置,因为在大多数情况下,
$http.get
尚未调用then/success回调

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

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


但是,请注意,如果在
YPosts
完成之前调用了
logoutUser
函数,那么
console.log(self.posts)
将再次显示
未定义的

返回语句仅从其函数范围返回。Javascript倾向于鼓励将回调传递给长时间运行的函数,以便代码不会阻止其他活动。如果要在get请求解决后获得POST的值,请让
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);
            });
        }
编辑:

像这样调用ypost:

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

我是返回
posts
还是返回
self.posts
?在这两种情况下,当我单击“注销”时,我的前端仍然显示
undefined
:。在我的前端,我也在浏览self.posts,但是什么也没有显示(意思是它是空的)。啊,我真的明白你的意思了。我的答案是错的。我来换;-)更新!就是这样,对吗?我的
控制台.log()后面有
返回帖子
函数:)Meh.:-)(很晚了;-))。但是我现在知道答案了-假设您的
XPosts
也不起作用。当我尝试此代码时,可能会出现重复的错误,即
回调不是函数。知道为什么吗?听起来好像你没有把回调参数传递给
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);
            });
        }
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