问题描述
限时送ChatGPT账号..我使用 angularfire 将数据保存到我的 Firebase 中.这是一个快速代码.
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');
我已成功将这些数据发送到我的 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?
编辑
所以在实现 then() 函数之后.
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.');
});
连接到互联网时.then() 函数很好.在显示警报之前,它会等待这些数据保存在 firebase 中.我想要的是它告诉我数据没有保存.当我关闭互联网连接并提交这些数据时,捕获错误功能未触发.
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.
推荐答案
当你调用 $add()
时,它会返回一个 promise.要检测数据何时保存,请实现 then()
.要检测何时保存失败,请实现 catch()
:
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);
});
请参阅文档add()
.
检测何时由于没有网络连接而无法保存数据对于 Firebase 数据库来说是一个非常不同的问题.在这种情况下无法保存不是错误,而只是暂时的情况.这个条件不仅仅适用于这个 set()
操作,而是适用于所有读/写操作.因此,您应该通过 更全面地处理它检测连接状态:
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");
}
});
通过侦听 .info/connected
,您的代码可以知道用户未连接到 Firebase 数据库并根据您的应用的需要进行处理.
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.
这篇关于将数据添加到 firebase 时,如何在 Angularfire 上未发送数据时捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论