0

我有一个使用 angular-meteor 构建的相当简单的应用程序。下面是我的 app.js 文件。当用户登录时,他们被重定向到家庭状态。通常,$rootScope.currentUser 存在,并且我能够获取我需要在视图中显示的用户数据等。但是有时在刷新时,我收到一条错误消息,指出 $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);
            }
          )
        );
    });

}
4

3 回答 3

2

首先,就像@Matt 提到的那样,您需要修复 $rootScope/$scope 问题。那么在路由中,您可以在需要用户的任何路由上使用 resolve 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 在用户订阅开始之前不会被填充。

于 2015-07-31T20:20:27.200 回答
0

即使我$meteor.waitForUser()在解析中使用,我有时也会在刷新时得到 $rootScope.currentUser 未定义。

所以我尝试了这个Meteor.users.findOne(Meteor.userId())

但即使有时它不起作用。这个解决方案对我不起作用。

我在$rootScope.$on('$stateChangeSuccess', ...函数中使用 $rootScope.currentUser 因为我需要对用户进行一些检查。

于 2015-12-24T12:45:56.783 回答
0

您已经在您的依赖声明$rootScope$scope混为一谈了。

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

应该 ...

.controller('card-stack', ['$rootScope', '$scope', '$state', '$meteor', function ($rootScope, $scope, $state, $meteor) {
于 2015-07-29T23:18:51.937 回答