问题
Let say I want to retrieve user info from firebase, and this user info will be displayed in several routes/controllers
Should I $rootScope
the returned user info?
or
Call below code in each controller?
firebaseAuth.firebaseRef.child('/people/' + user.id).on('value', function(snapshot) {
$scope.user = snapshot.val();
})
UPDATE
I have a following service with a getUserInfo()
function then what is the best way
to use it in several controllers?
calling firebaseAuth.getUserInfo().then()
in each controller?
If the user data I have to use in several controller. Why don't I set it $rootScope
?
So I don't need to call it again and again in different controllers.
myapp.service('firebaseAuth', ['$rootScope', 'angularFire', function($rootScope, angularFire) {
this.firebaseRef = new Firebase("https://test.firebaseio.com");
this.getUserInfo = function(id) {
var userRef = this.firebaseRef.child('/human/' + id);
var promise = angularFire(userRef, $rootScope, 'user', {});
return promise;
}
});
回答1:
The point of AngularFire is to keep your javascript data model in sync with Firebase at all times. You don't want to create a new AngularFire promise every time you need to fetch data. You just initialize AngularFire once, and your local data will always be up to date.
myapp.service('firebaseAuth', ['angularFireCollection', function(angularFireCollection) {
this.firebaseRef = new Firebase("https://test.firebaseio.com");
this.initUserInfo = function(id) {
if (!this.userRef) {
this.userRef = this.firebaseRef.child('/human/' + id);
this.userInfo = angularFireCollection(this.userRef);
}
else {
// already initialized
}
}
}]);
Remember that all properties of your service (i.e. everything you assign using the this
keyword) are accessible from controllers injected with this service. So you can do things like console.log(firebaseAuth.userInfo)
or firebaseAuth.userRef.on('value', function(snap) { ... });
Also, you may eventually want to use the FirebaseAuthClient for your user authentication.
回答2:
I would recommend creating a service to perform the authentication and store the user data. Then you can inject the service into any controller that needs access to the user.
来源:https://stackoverflow.com/questions/17026374/angularjs-should-i-rootscope-data-returned-from-firebase