简体   繁体   English

角流星$ rootScope.currentUser未定义

[英]angular-meteor $rootScope.currentUser is undefined

I have a fairly simple application I am building using angular-meteor. 我有一个使用角流星构建的相当简单的应用程序。 Below is my app.js file. 以下是我的app.js文件。 When a user logs in, they are redirected to the home state. 用户登录时,他们将被重定向到家庭状态。 Usually, $rootScope.currentUser exists, and I am able to get the user data I need to display in the views, etc. However sometimes on refresh, I am getting an error saying $rootScope.currentUser is undefined. 通常,$ rootScope.currentUser存在,并且我能够获取需要在视图中显示的用户数据,等等。但是有时刷新时,我会收到一条错误消息,指出$ rootScope.currentUser是未定义的。 I'm pretty sure the Meteor users collection is sometimes not ready yet when I try to access it, but I can't figure out how to make sure this happens every time. 我很确定当我尝试访问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);
            }
          )
        );
    });

}

First, like @Matt mentions, you need to fix your $rootScope/$scope issue. 首先,就像@Matt提到的那样,您需要修复$ rootScope / $ scope问题。 THen in the routes you can use resolve on any route that needs a user with waitForUser() : 在路由中,可以在需要使用waitForUser()的用户的任何路由上使用resolve

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

This will return the user subscription or null if not logged in. Sometimes $rootScope.currentUser isn't filled until the users subscription is started. 这将返回用户订阅;如果未登录,则返回null。有时,直到开始用户订阅时,才会填充$ rootScope.currentUser。

You have $rootScope and $scope mixed up in your dependency declaration for a start. 首先,在依赖声明中混合了$rootScope$scope

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

should be ... 应该 ...

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

I sometimes got the $rootScope.currentUser undefined when I refresh even if I use $meteor.waitForUser() in resolve. 即使刷新时使用$meteor.waitForUser() ,刷新时有时也会得到$ rootScope.currentUser未定义。

So I tried with this Meteor.users.findOne(Meteor.userId()) 所以我尝试了这个Meteor.users.findOne(Meteor.userId())

But even though sometimes it is not working. 但是,即使有时它不起作用。 this solution doesn't work for me. 此解决方案对我不起作用。

I use $rootScope.currentUser in the $rootScope.$on('$stateChangeSuccess', ... function because I need to do some check on the user. 我在$rootScope.$on('$stateChangeSuccess', ...函数中使用$ rootScope.currentUser,因为我需要对用户进行一些检查。

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

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