How to check if data exists in firebase using angu

2019-03-31 14:49发布

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.');
            });

};

2条回答
狗以群分
2楼-- · 2019-03-31 15:25

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.

查看更多
Root(大扎)
3楼-- · 2019-03-31 15:49

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$;
}
查看更多
登录 后发表回答