如何获取经过身份验证的用户信息并在所有控制器和服务中使用? [英] How to get the authenticated user info and use in all controllers and services?
问题描述
我正在使用 angularFireAuth 并且我想检索登录用户的信息并在应用初始时的所有控制器或服务.
I'm using angularFireAuth and I want to retrieve the logged in user's info and use in all the controllers or services when the app is initial.
目前,我在每个控制器中都使用了它,但我遇到了一些问题.
Currently, I used this in every controller but i having some problem.
$scope.$on("angularFireAuth:login", function(evt, user){
console.log(user);
});
如果不是完整页面加载或应用初始化时返回null,则回调将不会调用.
The callback will not call if it is not a full page load or return null when app initial.
我需要一些关于如何返回经过身份验证的用户信息的提示,以便我可以在应用程序初始时以及在所有控制器和服务中使用.
I need some tips for how can I return the authenticated user's info so I can use when app is initial and in all the controllers and services.
示例
在控制器或服务中时
$scope.auth.user.id
将返回用户 ID$scope.auth.user.name
将返回用户名- 等
$scope.auth.user.id
will return user's ID$scope.auth.user.name
will return user's name- etc
推荐答案
为此,我会从 userService
开始:
I would start with a userService
for this:
angular.module('EventBaseApp').service('userService', function userService() {
return {
isLogged: false,
username: null
}
});
并编写一个LoginCtrl
控制器:
angular.module('EventBaseApp')
.controller('LoginCtrl', function ($scope, userService, angularFireAuth) {
var url = "https://example.firebaseio.com";
angularFireAuth.initialize(url, {scope: $scope, name: "user"});
$scope.login = function() {
angularFireAuth.login("github");
};
$scope.logout = function() {
angularFireAuth.logout();
};
$scope.$on("angularFireAuth:login", function(evt, user) {
userService.username = $scope.user;
userService.isLogged = true;
});
$scope.$on("angularFireAuth:logout", function(evt) {
userService.isLogged = false;
userService.username = null;
});
});
将 userService
注入到您想要用户的任何位置.
Inject the userService
anywhere you want the user.
我目前正在开发的应用程序使用了这个 - https://github.com/manojlds/EventBase/blob/master/app/scripts/controllers/login.js
My app that am currently working on that uses this - https://github.com/manojlds/EventBase/blob/master/app/scripts/controllers/login.js
基于此处提出的想法 - http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app
Based on ideas presented here - http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app
这篇关于如何获取经过身份验证的用户信息并在所有控制器和服务中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!