gpt4 book ai didi

javascript - Angular meteor $rootScope.currentUser 未定义

转载 作者:行者123 更新时间:2023-12-02 15:53:57 27 4
gpt4 key购买 nike

我正在使用 angular-meteor 构建一个相当简单的应用程序。下面是我的 app.js 文件。当用户登录时,他们会被重定向到主状态。通常, $rootScope.currentUser 存在,并且我能够获取需要在 View 等中显示的用户数据。但是有时在刷新时,我收到一条错误消息,指出 $rootScope.currentUser 未定义。我很确定当我尝试访问 Meteor 用户集合时,有时它还没有准备好,但我不知道如何确保每次都会发生这种情况。

Cards = new Mongo.Collection("cards");
Dopewaks = new Mongo.Collection("votes");
Userstats = new Mongo.Collection("userstats");
Votes = new Meteor.Collection("cardStore");

if (Meteor.isClient) {

Meteor.subscribe("votes");
Meteor.subscribe("dopewaks");
Meteor.subscribe("cardStore");

angular.module('dopewak', ['angular-meteor', 'ui.router', 'gajus.swing'])

function onReady() {
angular.bootstrap(document, ['dopewak']);
}

if (Meteor.isCordova)
angular.element(document).on("deviceready", onReady);
else
angular.element(document).ready(onReady);

angular.module('dopewak').config(['$urlRouterProvider', '$stateProvider', '$locationProvider',
function($urlRouterProvider, $stateProvider, $locationProvider){

$locationProvider.html5Mode(true);

$stateProvider
.state('login', {
url: '/login',
templateUrl: 'login.ng.html',
controller: 'card-stack'
})
.state('home', {
url: '/home',
templateUrl: 'index.ng.html',
controller: 'card-stack'
});

$urlRouterProvider.otherwise('/login');
}]);


angular.module('dopewak').controller('card-stack', ['$rootScope', '$scope', '$state', '$meteor', function ($scope, $rootScope, $state, $meteor) {

$scope.dopelist = $meteor.collection(Votes);

if ($state.is('home')) {

console.log($rootScope.currentUser);

if( $rootScope.currentUser.services.hasOwnProperty("twitter") ) {
$scope.profilePic = $rootScope.currentUser.services.twitter.profile_image_url;
$scope.screenName = $rootScope.currentUser.services.twitter.screenName;
} else if($rootScope.currentUser.services.hasOwnProperty("facebook")) {
console.log("facebook");
}

$scope.userStats = $meteor.collection(Userstats);
}

$scope.cardCount = $meteor.collection(Cards).length;
var cards = $meteor.collection(Cards);
var currentIndex = cards.length, temporaryValue, randomIndex ;

// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = cards[currentIndex];
cards[currentIndex] = cards[randomIndex];
cards[randomIndex] = temporaryValue;
}

$scope.cards = cards;


$scope.throwoutleft = function (eventName, eventObject) {
var card = eventObject.target;
var cardID = Dopewaks.insert({ name: eventObject.target.id, userID: $rootScope.currentUser._id, vote: 2, time: new Date().valueOf() });

var doc = Cards.findOne({ "name": eventObject.target.id });
Cards.update({ _id: doc._id }, {$inc: { dopescore: -1 }});
$scope.cardCount--;

var user = Userstats.findOne({ "name": $rootScope.currentUser.profile.name });
var username = $rootScope.currentUser.profile.name;

if(typeof user === 'undefined') {
Userstats.insert( { name: username , waks: 1 } );
} else {
var record = Userstats.findOne({ "name": username });
Userstats.update({ _id: record._id }, {$inc: { waks: 1 }});
}

$('.wak-tip').addClass('animated rubberBand');
$('.wak-tip').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$('.wak-tip').removeClass('animated rubberBand');
});

};

$scope.throwoutright = function (eventName, eventObject) {
var card = eventObject.target;
var cardID = Dopewaks.insert({ name: eventObject.target.id, userID: $rootScope.currentUser._id, vote: 1, time: new Date().valueOf() });

var doc = Cards.findOne({ "name": eventObject.target.id });
Cards.update({ _id: doc._id }, {$inc: { dopescore: 1 }});
$scope.cardCount--;

var user = Userstats.findOne({ "name": $rootScope.currentUser.profile.name });
var username = $rootScope.currentUser.profile.name;

if(typeof user === 'undefined') {
Userstats.insert( { name: username , dopes: 1 } );
} else {
var record = Userstats.findOne({ "name": username });
Userstats.update({ _id: record._id }, {$inc: { dopes: 1 }});
}

$('.dope-tip').addClass('animated rubberBand');
$('.dope-tip').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$('.dope-tip').removeClass('animated rubberBand');
});
};

$scope.throwout = function (eventName, eventObject) {
var card = eventObject.target;
$(card).css('display', 'none');
};

$scope.addCard = function(newCard) {
$scope.addMessage = false;

var cardExist = Cards.find({lowerName: newCard.name.toLowerCase()}, {limit: 1}).count() > 0;

if(newCard.name.length < 2) {
$scope.addMessage = 'Entry must contain at least 2 letters.';
} else if(cardExist) {
$scope.addMessage = 'This card already exists. Try another thing.';
} else {
Cards.insert({ name: newCard.name, lowerName: newCard.name.toLowerCase(), userID: $rootScope.currentUser._id, time: new Date() });
$scope.addMessage = 'Your card was successfully added!';
}
}

$scope.openUpload = function() {
$('.submit-overlay').show();
};

$scope.closeUpload = function() {
$('.submit-overlay').hide();
};

$scope.toggleLeftMenu = function() {
if($("#left-menu").hasClass("menu-visible")) {
$scope.leftMenuShown = false;
$('.modal-bg').css('display', 'none');
$("#left-menu").removeClass("menu-visible");
$("#left-menu").animate({
left: '-250px'
}, 300);
} else {
$scope.leftMenuShown = true;

if($scope.rightMenuShown) {
$scope.toggleRightMenu();
}

$('.modal-bg').css('display', 'block');
$("#left-menu").addClass("menu-visible");
$("#left-menu").animate({
left: '0'
}, 300);
}
};

$scope.toggleRightMenu = function() {
if($("#right-menu").hasClass("menu-visible")) {
$scope.rightMenuShown = false;
$('.modal-bg').css('display', 'none');
$("#right-menu").removeClass("menu-visible");
$("#right-menu").animate({
right: '-250px'
}, 300);
} else {
$scope.rightMenuShown = true;

if($scope.leftMenuShown) {
$scope.toggleLeftMenu();
}

$('.modal-bg').css('display', 'block');
$("#right-menu").addClass("menu-visible");
$("#right-menu").animate({
right: '0'
}, 300);
}
};

$scope.checkMenus = function() {
if($scope.leftMenuShown) {
$scope.toggleLeftMenu();
}

if($scope.rightMenuShown) {
$scope.toggleRightMenu();
}
};

Accounts.onLogin(function () {
if ($state.is('login')) {
$state.go('home');
}
});

Accounts.onLoginFailure(function () {
$state.go('login');
});

}]);

}

if (Meteor.isServer) {
Meteor.startup(function () {
if (Cards.find().count() === 0) {

var cards = [
{'name': 'Test1'},
{'name': 'Test2'},
{'name': 'Test3'}
];

for (var i = 0; i < cards.length; i++)
Cards.insert(cards[i]);

}
});

Votes.allow({
'insert': function (userId,doc) {
/* user and doc checks ,
return true to allow insert */
return true;
}
});

Dopewaks.allow({
'insert': function (userId,doc) {
/* user and doc checks ,
return true to allow insert */
return true;
}
});

Cards.allow({
'insert': function (userId,doc) {
/* user and doc checks ,
return true to allow insert */
return true;
}
});

Cards.allow({
'update': function (userId,doc) {
/* user and doc checks ,
return true to allow insert */
return true;
}
});

Userstats.allow({
'insert': function (userId,doc) {
/* user and doc checks ,
return true to allow insert */
return true;
}
});

Userstats.allow({
'update': function (userId,doc) {
/* user and doc checks ,
return true to allow insert */
return true;
}
});

Meteor.publish("votes", function(args) {
var sub = this;

var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

var pipeline = [
{ "$group": {
"_id": "$name",
"likes": { "$sum": { "$cond": [{ "$eq": [ "$vote", 1 ] },1,0] } },
"dislikes": { "$sum": { "$cond": [{ "$eq": [ "$vote", 2 ] },1,0] } },
"total": { "$sum": { "$cond": [{ "$eq": [ "$vote", 1 ] },1,-1] } }
}},
{ "$sort": { "total": -1, "_id": 1 } }

];

db.collection("votes").aggregate(
pipeline,
Meteor.bindEnvironment(
function(err, result) {
_.each(result, function(e) {
e.name = e._id;
delete e._id;

sub.added("cardStore",Random.id(), e);

});
sub.ready();
},
function(error) {
Meteor._debug( "error running: " + error);
}
)
);
});

}

最佳答案

首先,就像 @Matt 提到的那样,您需要修复 $rootScope/$scope 问题。然后在路由中,您可以在需要用户 waitForUser(): 的任何路由上使用解析

 angular.module('dopewak').config(['$urlRouterProvider', '$stateProvider', '$locationProvider',
function($urlRouterProvider, $stateProvider, $locationProvider){

$locationProvider.html5Mode(true);

$stateProvider
.state('login', {
url: '/login',
templateUrl: 'login.ng.html',
controller: 'card-stack',
resolve: {
'currentUser': ['$meteor', function($meteor) {
$meteor.waitForUser();
}]
}
})
.state('home', {
url: '/home',
templateUrl: 'index.ng.html',
controller: 'card-stack'
});

$urlRouterProvider.otherwise('/login');
}]);

这将返回用户订阅,如果未登录,则返回 null。有时 $rootScope.currentUser 在用户订阅启动之前不会填充。

关于javascript - Angular meteor $rootScope.currentUser 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31712728/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com