在AngularFire,为什么在控制器中的auth.user财产空,但没有看法? [英] In AngularFire, why is the auth.user property null in the controller, but not the view?
问题描述
有登录到火力地堡用户,并在我的看法,$ scope.auth返回当前登录的用户,我可以访问其数据。
There is a user logged into Firebase, and in my views, $scope.auth returns the current logged in user and I can access its data.
在我然而控制器,$ scope.auth.user返回null。
In my controller however, $scope.auth.user returns null.
myApp.controller('quoteController', ['$scope', '$firebase', '$firebaseSimpleLogin',
function($scope, $firebase, $firebaseSimpleLogin) {
$scope.auth = $firebaseSimpleLogin(dataRef);
console.log($scope.auth.user);
});
的console.log($ scope.auth.user)=='空'。
console.log($scope.auth.user) == 'null'.
为什么会出现这种情况?我知道,用户登录该angularFire文档说,简单登录登录状态是全局应用程序,即使创建了多个$ firebaseSimpleLogin对象。所以,不应该$ scope.auth.user包含当前用户?
Why is this the case? I know that the user is logged in. The angularFire docs says that, "the login state for Simple Login is global to your application, even if multiple $firebaseSimpleLogin objects are created." So shouldn't $scope.auth.user contain the current user?
推荐答案
登录需要异步联系服务器。不能立即访问变量从下一行的,因为它尚未检索。此外,您还需要调用一个用户对象之前登录()将存在。假设有一个登录从另一个页面视图,或登录()持续被调用,您可以采取一些方法来完成你想要的。
Login requires contacting the server asynchronously. You can't immediately access the variable on the next line because it hasn't been retrieved yet. Additionally, you'll need to call login() before a user object will exist. Assuming there is a login persisted from another page view, or login() has been called, you can take a few approaches to accomplish what you want.
使用 $ getCurrentUser()等待身份验证过程解析并获取当前认证的用户帐户:
Use $getCurrentUser() to wait for the auth process to resolve and fetch the user account that is currently authenticated:
angular.module("sampleApp", ["firebase"])
.controller("SampleController", ["$scope", "$firebase", "$firebaseSimpleLogin",
function($scope, $firebase, $firebaseSimpleLogin) {
var ref = new Firebase("https://<my-firebase>.firebaseio.com/");
$scope.auth = $firebaseSimpleLogin(ref);
$scope.auth.$getCurrentUser().then(function(user) {
console.log(user);
});
}
]);
利用 AUTH事件的:
angular.module("sampleApp", ["firebase"])
.controller("SampleController", ["$scope", "$firebase", "$firebaseSimpleLogin",
function($scope, $firebase, $firebaseSimpleLogin) {
var ref = new Firebase("https://<my-firebase>.firebaseio.com/");
$scope.auth = $firebaseSimpleLogin(ref);
$scope.$on('$firebaseSimpleLogin:login', function() {
console.log($scope.auth.user);
});
}
]);
或者您可以使用的承诺时返回登录正所谓:
angular.module("sampleApp", ["firebase"])
.controller("SampleController", ["$scope", "$firebase", "$firebaseSimpleLogin",
function($scope, $firebase, $firebaseSimpleLogin) {
var ref = new Firebase("https://<my-firebase>.firebaseio.com/");
$scope.auth = $firebaseSimpleLogin(ref);
$scope.auth.$login('twitter').then(function() {
console.log($scope.auth.user);
});
}
]);
这篇关于在AngularFire,为什么在控制器中的auth.user财产空,但没有看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!