Expose current logged in user globally in Angular and Firebase

我们两清 提交于 2020-01-16 05:18:10

问题


I'm looking for a clear and elegant way to have the current logged in user exposed everywhere in my app because I have a navigation partial view that contains the user information as well as a logout button but I haven't been able to accomplish that.

My starting point is this sample app https://github.com/firebase/angularfire-seed and I just added an AppCtrl where I can expose the current logged in user. I have tried adding the user provider but that doesn't work either.

controllers.js

.controller('AppCtrl', ['$scope', '$rootScope','simpleLogin', 'fbutil', '$location', function($scope, $rootScope, simpleLogin, fbutil, $location) {
  $scope.user = simpleLogin.getUser();
  $scope.logout = function() {
    var profile = fbutil.syncObject(['users', simpleLogin.getUser().uid]);
    profile.$destroy();
    simpleLogin.logout();
    $location.path('/login');
  };
}])

index.html

<body ng-controller="AppCtrl">

Your help will be very appreciated.


回答1:


Take a look at the resolve parameter - this exists both in $routerProvider and $stateProvide. resolve resolves the objects (including resolving a promise) and then these objects are available to your controllers. In this case, you "resolve" your loggedInUser variable (by doing whatever you need to do via your authentication service.

$routeProvider
   .when("/someSecuredContent", {
     templateUrl: 'someSecuredContent.html',
     controller: 'SecuredController',
     resolve: {
        loggedInUser: function(MyAuth){
           return MyAuth.loggedIn(); // MyAuth.loggedIn() should return a $q promise
        }
     }
});

Then in the controller, loggedInUser will be injected.

Here's a site with more examples.




回答2:


After using multiple methods for exposing the current logged in user globally, I think it is best described in this tutorial, specifically in the "Accessing the current user throughout the application" section. Also the tutorial is awesome and I think they have got the architecture right for this type of application.



来源:https://stackoverflow.com/questions/26049927/expose-current-logged-in-user-globally-in-angular-and-firebase

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