How to check if data exists in firebase using angularfire?

和自甴很熟 提交于 2019-12-05 02:10:00

问题


I would like to register users manually in firebase. How can i check if the user is registered already or if his ( USERID ) exists? If it exists it should not let him register otherwise if his userid is not yet on the database then his info should be saved. Here is my current code wherein only saving userinfo is still available.

$scope.details={};

$scope.registerme= function() {
var someDate = new Date();
var ref = firebase.database().ref('/Users/');
$scope.submitme = $firebaseArray(ref);


            $scope.submitme.$add({
            facebookid: $scope.details.userid,
            firstname: $scope.details.firstname,
            lastname: $scope.details.lastname,
            timestamp: someDate.toString(),
            }).then(function(ref) {
            alert('Registration success.');
            }).catch(function(error) {
            alert('Registration Failed.');
            });

};

回答1:


There is nothing built into AngularFire for detecting if a node exists. But since AngularFire is built on top of the Firebase JavaScript SDK, you can do this with the JavaScript API:

ref.child(uid).once('value', function(snapshot) {
    console.log(snapshot.exists());
});

The important thing to realize is that this snippet uses a value event, which will fire null if there is no data at the current location.

A $firebaseArray() from AngularFire on the other hand uses Firebase's child_* events, which cannot be used to detect existence of a specific child in the collection.




回答2:


If you set up a link to your db entity as FirebaseObjectObservable, then you can use exists() to check if your entity exists. That how I check if my table exists and if not, I'll fill it with initial data:

vehicle.service.ts:

...
public vehicles$$: FirebaseObjectObservable<any>; // link to '/vehicles' as object
public vehicles$ FirebaseListObservable<Vehicle[]>; // link to '/vehicles' as list 
...
constructor(
  private _http: Http, 
  private _db: AngularFireDatabase,

) { 
  this.vehicles$$ = _db.object('/vehicles'); 
  this.vehicles$ = _db.list('/vehicles');
}


public getVehicles(){
  this.vehicles$$.subscribe(table => {
    if(!table.$exists()){          
      this.getVehiclesFromFile().subscribe(vehicles(vehicles: Vehicle[]) =>
        this.vehicles$$.set(vehicles).catch(err=>console.error(err))
      )
    }
  })
  return this.vehicles$;
}


来源:https://stackoverflow.com/questions/39234521/how-to-check-if-data-exists-in-firebase-using-angularfire

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