Angularjs 尝试使用AngularFire匿名验证用户时获取Websocket失败
我正在尝试使用AngularFire匿名验证用户。我只想对用户进行一次身份验证(因此,如果用户已经过身份验证,则不会生成新的uid)。当我使用下面的代码时,我会收到一个Angularjs 尝试使用AngularFire匿名验证用户时获取Websocket失败,angularjs,firebase,angularfire,Angularjs,Firebase,Angularfire,我正在尝试使用AngularFire匿名验证用户。我只想对用户进行一次身份验证(因此,如果用户已经过身份验证,则不会生成新的uid)。当我使用下面的代码时,我会收到一个以前的\u websocket\u失败通知。控制台中还有一个错误,上面写着TypeError:cannotreadproperty'uid'of null。刷新页面后,一切正常 你觉得我做错了什么吗 app.factory('Ref', ['$window', 'fbURL', function($window, fbURL) {
以前的\u websocket\u失败
通知。控制台中还有一个错误,上面写着TypeError:cannotreadproperty'uid'of null
。刷新页面后,一切正常
你觉得我做错了什么吗
app.factory('Ref', ['$window', 'fbURL', function($window, fbURL) {
'use strict';
return new Firebase(fbURL);
}]);
app.service('Auth', ['$q', '$firebaseAuth', 'Ref', function ($q, $firebaseAuth, Ref) {
var auth = $firebaseAuth(Ref);
var authData = Ref.getAuth();
console.log(authData);
if (authData) {
console.log('already logged in with ' + authData.uid);
} else {
auth.$authAnonymously({rememberMe: true}).then(function() {
console.log('authenticated');
}).catch(function(error) {
console.log('error');
});
}
}]);
app.factory('Projects', ['$firebaseArray', '$q', 'fbURL', 'Auth', 'Ref', function($firebaseArray, $q, fbURL, Auth, Ref) {
var authData = Ref.getAuth();
var ref = new Firebase(fbURL + '/projects/' + authData.uid);
console.log('authData.uid: ' + authData.uid);
return $firebaseArray(ref);
}]);
在项目工厂中,您假设
authData
将不为空。这里没有任何保证,因为一旦您将项目工厂注入另一个提供程序,它就会被初始化。我还注意到,您的身份验证服务实际上并没有返回任何内容。这可能意味着调用者必须知道内部工作,并导致相当多的耦合。更坚实的结构可能如下所示:
app.factory('Projects', function(Ref, $firebaseArray) {
// return a function which can be invoked once
// auth is resolved
return function(uid) {
return $firebaseArray(Ref.child('projects').child(uid));
}
});
app.factory('Auth', function(Ref, $firebaseAuth) {
return $firebaseAuth(Ref);
});
app.controller('Example', function($scope, Auth, Projects) {
if( Auth.$getAuth() === null ) {
auth.$authAnonymously({rememberMe: true}).then(init)
.catch(function(error) {
console.log('error');
});
}
else {
init(Auth.$getAuth());
}
function init(authData) {
// when auth resolves, add projects to the scope
$scope.projects = Projects(authData.uid);
}
});
请注意,通常不鼓励在控制器和服务中处理auth,处理这一问题是一个更优雅的解决方案我强烈建议投资于这种方法。查看一些示例代码