How to Catch Error When Data is not Sent on Angula

2019-09-16 02:29发布

问题:

Im using angularfire to save data into my firebase. Here is a quick code.

$scope.users.$add({ 
            Name:$scope.username,
            Age:$scope.newage,
            Contact: $scope.newcontact,
          });

 alert('Saved to firebase');

I am successful in sending these data to my firebase however how can I catch an error if these data are not saved successfully? Any ideas?

EDIT

So after implementing then() function.

$scope.users.$add({   
        Name:'Frank',
        Age:'20',
        Contact: $scope.newcontact,
      }).then(function(ref) {
 alert('Saved.');
 }).catch(function(error) {
 console.error(error); //or
 console.log(error);
 alert('Not Saved.');
 });

When connected to the internet. The then() function is fine. It waits for those data to be saved in firebase before showing the alert. What I want is for it to tell me that data is not saved. catch error function is not firing when i am turning off my internet connection and submitting those data.

回答1:

When you call $add() it returns a promise. To detect when the data was saved, implement then(). To detect when saving failed, implement catch():

var list = $firebaseArray(ref);
list.$add({ foo: "bar" }).then(function(ref) {
  var id = ref.key;
  console.log("added record with id " + id);
  list.$indexFor(id); // returns location in the array
}).catch(function(error) {
  console.error(error);
});

See the documentation for add().

Update

To detect when the data cannot be saved due to not having a network connection is a very different problem when it comes to the Firebase Database. Not being able to save in this case is not an error, but merely a temporary condition. This condition doesn't apply just to this set() operation, but to all read/write operation. For this reason, you should handle it more globally, by detecting connection state:

var connectedRef = firebase.database().ref(".info/connected");

connectedRef.on("value", function(snap) {
  if (snap.val() === true) {
    alert("connected");
  } else {
    alert("not connected");
  }
});

By listening to .info/connected your code can know that the user is not connected to the Firebase Database and handle it according to your app's needs.