How to Catch Error When Data is not Sent on Angularfire when adding data to firebase?

风格不统一 提交于 2019-12-12 03:49:19

问题


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.



来源:https://stackoverflow.com/questions/38805715/how-to-catch-error-when-data-is-not-sent-on-angularfire-when-adding-data-to-fire

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