带有userid引用的$ firebase,用户登录后的init最佳实践?

时间:2014-06-29 14:03:23

标签: firebase angularfire

就像firefeed一样,我将user-meta存储在/ users / userid下。

我只需要当前登录用户的元数据,因此我的想法是仅为登录用户获取引用。而不是

usersRef = new Firebase(firebase/users/) && users = $firebase(usersRef)

我要等到登录服务设置当前用户,然后根据该用户的id创建引用。这是在服务内部。

    var userRef = undefined;
    var user = undefined;

var _setCurrentUser = function (passedUser) {
        console.log(passedUser);
        currentUser = passedUser;
        if (!currentUser) {
        userRef = new Firebase(FIREBASE_URI + 'users/' + currentUser.id);
        user = $firebase(userRef);
        }
    };

我的问题是:这是个好主意吗?如果我不需要对整个用户对象的引用,那么指定特定用户在性能方面是否有意义。怎么样/以什么方式?是否有更好的方法可以等到我们拥有当前用户的id来为用户创建firebase实例?

1 个答案:

答案 0 :(得分:2)

理想情况下,如果您不需要所有用户,则可以获取特定参考。如下所示:

var app = angular.module('myApp', ['firebase']);

// a little abstraction to manage establishing a $firebaseSimpleLogin instance
app.factory('loginService', function($firebaseSimpleLogin, Firebase) {
   var fb = new Firebase(URL);
   var auth = $firebaseSimpleLogin(fb);
   return auth;
});

// a little abstraction to reduce the deps involved in creating a $firebase object
app.factory('syncData', function($firebase, Firebase) {
   return function(pathToData) {
      return $firebase(new Firebase(URL).child(pathToData));
   }
});

app.factory('logInAndReturnUser', function(loginService, syncData) {
   return function(provider) {
      // call the login service
      return loginService.$login(provider)
         .then(function(user) {
            // resolve to a $firebase object for the specific user
            return syncData('users/'+user.uid);
         });
   }
});

Angular-ui的ui-router是这种用例的理想选择,我强烈推荐这种方法来处理auth。只需设置一个返回用户的resolve

var app = angular.module('myApp', ['firebase']);

app.factory('loginService', function($firebaseSimpleLogin, Firebase) {
   var fb = new Firebase(URL);
   var auth = $firebaseSimpleLogin(fb);
   return auth;
});

app.configure(function($stateProvider) {
   $stateProvider.state('home', {
      url: '/',
      resolve: {
        'user': function(loginService) {
           // getCurrentUser returns a promise that resolves to the user object
           // or null if not logged in
           return loginService.$getCurrentUser();
        }
      },
      controller: 'homeCtrl'
    })
});

app.controller('homeCtrl', function(user) {
   // assumes we've logged in already, that can be part of router
   // processing or we could check for user === null here and send to login page
   console.log('user is ' + user.uid); 
});