How to use angularFireAuth values in controllers and services?

断了今生、忘了曾经 提交于 2019-12-10 12:12:28

问题


Let say I put angularFireAuth inside a service.

app.factory('authService',
function($rootScope, $timeout, angularFireAuth, FIREBASE_URL) {
    return function() {
        angularFireAuth.initialize(new Firebase(FIREBASE_URL), {
            scope: $rootScope,
            name: 'user',
            path: "/"
        });
        $rootScope.$on('angularFireAuth:login', function _set(evt, user) {
            $timeout(function() {
                $rootScope.auth = {
                    authenticated: true
                   };
            });
         });
        $rootScope.$on('angularFireAuth:logout', function(){
            $timeout(function() {
                $rootScope.auth = {
                    authenticated: false
                   };
            });    
        });
      }
    });

Then I initial it in .run()

.run(['$rootScope', 'authService', function($rootScope, authService){
  authService();
});

My question is how can I use $scope.auth.authenticated in other services and controllers.

I console.log($scope.auth.authenticated) in controller. It always return false. Seem like it is not listening / watching the login

Or

Can I use $scope.user directly in controller and listening on it?

UPDATE

I created a plunker.


回答1:


The problem is that $scope.user (and by extension $scope.auth) are not created until the login takes place, which isn't until one clicks the login button. But the console.log event takes place as soon as the controller is created (onDOMReady).

You probably don't need the $scope.auth at all. Firereader is using that because it needs some additional data put into the user object and specifically a boolean which is used in an ng-switch statement. In your case, you can probably just use $scope.user, which is set by angularFireAuth and not bother with the $scope.auth object.

So, to summarize, if you move your console.log to wait until the login is completed, it will work as expected: http://plnkr.co/edit/Bd23DGFtEpqO2g4jo06v?p=preview

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

app.constant('FIREBASE_URL', 'https://newname.firebaseio.com/');
app.run(['$rootScope', 'authService', function($rootScope, authService){
    authService();
    $rootScope.$watch('auth.authenticated', function() {
        isAuthenticated = $rootScope.auth.authenticated;
    });
}]);

app.factory('authService', [
    '$rootScope',
    '$timeout',
    'angularFireAuth',
    'FIREBASE_URL',

    function($rootScope, $timeout, angularFireAuth, FIREBASE_URL) {
        return function() {
            angularFireAuth.initialize(new Firebase(FIREBASE_URL), {
                scope: $rootScope,
                name: 'user'
            });

            $rootScope.$on('angularFireAuth:login', _log);

            function _log(evt, user) {
                // this is where $scope.user and $scope.auth will be set
                  console.log($scope.user);
             }
        }
    }
]);



app.controller('MainCtrl', function($scope, authService, angularFireAuth) {
  $scope.name = 'World';

  $scope.login = function(){
    angularFireAuth.login('facebook');
  }

  $scope.logout = function(){
    angularFireAuth.logout();
  }

  // angularFireAuth hasn't returned yet at this point
  // console.log($scope.auth);
});



回答2:


Thanks to Tom Chen's second example I'm using angularfire's auth like so:

myapp.controller("UserController", ["$scope", "$firebase", "$firebaseSimpleLogin",       function($scope, $firebase, $firebaseSimpleLogin) {
var ref = new Firebase("https://XXXXXX.firebaseio.com/");
$scope.auth = $firebaseSimpleLogin(ref);

$scope.$watch('auth', function(newAuth, oldAuth){
    console.log(newAuth, oldAuth);
    // logged in, 
    // can reference newAuth.user.id
  }, true);

}]);

UPDATE

This example is also a call back

$scope.$on("$firebaseSimpleLogin:login", function(e, user) {
  // can reference user.id 
}); 



回答3:


One reason that i can think on why this is not working could be that the local scope is shadowing the variable declared on $rootScope. Maybe there has been an assignment to the local scope object auth. You can very much verify this in firebug or chrome tools by putting some breakpoints and verify values for both $rootScope.auth and $scope.auth.

Better to check when the auth completes within a child scope.




回答4:


I would replace angularFire with angular-on-fire and use the provided fireEntry service.

module('app.auth', ['angular-on-fire'])
.constant({FirebaseUrl: "https://YOUR_FB_NAME.firebaseIO.com/"})
.run(['$rootScope', 'fireEntry', function($rootScope, fireEntry){
  var auth = {};
  $rootScope.auth = auth;
  fireEntry(auth);
}]]);

So, any update to auth will reflected in the $rootScope auth variable.
If user logged in, auth will contain user information provided by FirebaseSimpleLogin. Once logged out, auth will be empty.

You can now watch on $rootScope.auth to receive any auth update!

module('app.ctrl', ['app.auth']).controller('HomeCtrl', ['$scope', function($scope){
  $scope.$watch('auth', function(newAuth, oldAuth){
    console.log(newAuth, oldAuth);
  }, true);
}]);


来源:https://stackoverflow.com/questions/18633691/how-to-use-angularfireauth-values-in-controllers-and-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!