【发布时间】:2018-04-26 08:47:17
【问题描述】:
如何在 angular2 应用程序中使用 firestore 进行批量写入/运行事务?
https://firebase.google.com/docs/firestore/manage-data/transactions
如果可能的话,如何在 angular2 应用程序中将 JS 代码转换为 TS 代码。
【问题讨论】:
标签: angular firebase google-cloud-firestore
如何在 angular2 应用程序中使用 firestore 进行批量写入/运行事务?
https://firebase.google.com/docs/firestore/manage-data/transactions
如果可能的话,如何在 angular2 应用程序中将 JS 代码转换为 TS 代码。
【问题讨论】:
标签: angular firebase google-cloud-firestore
如果您使用 AngularFirestore,首先您需要确保您的构造函数设置如下:
constructor(private db: AngularFirestore)
现在您可以使用 db.firestore 来获取 firebase.firestore 实例。
您可以从链接中复制代码并将 db 替换为 db.firestore。或者你可以使用箭头函数让它更漂亮:
使用事务更新数据:
// Create a reference to the SF doc.
const sfDocRef = db.firestore.collection("cities").doc("SF");
// Uncomment to initialize the doc.
// sfDocRef.set({ population: 0 });
db.firestore.runTransaction(transaction =>
// This code may get re-run multiple times if there are conflicts.
transaction.get(sfDocRef)
.then(sfDoc => {
const newPopulation = sfDoc.data().population + 1;
transaction.update(sfDocRef, { population: sfDoc.data().population + 1 });
})).then(() => console.log("Transaction successfully committed!"))
.catch(error => console.log("Transaction failed: ", error));
从交易中传递信息:
// Create a reference to the SF doc.
const sfDocRef = db.firestore.collection("cities").doc("SF");
db.firestore.runTransaction(transaction =>
transaction.get(sfDocRef).then(sfDoc => {
const newPopulation = sfDoc.data().population + 1;
if (newPopulation <= 1000000) {
transaction.update(sfDocRef, { population: newPopulation });
return newPopulation;
} else {
return Promise.reject("Sorry! Population is too big.");
}
}))
.then(newPop => console.log("Population increased to ", newPop)
).catch(err => console.error(err)); // This will be an "population is too big" error.
批量写入:
// Get a new write batch
var batch = db.firestore.batch();
// Set the value of 'NYC'
var nycRef = db.firestore.collection("cities").doc("NYC");
batch.set(nycRef, {name: "New York City"});
// Update the population of 'SF'
var sfRef = db.firestore.collection("cities").doc("SF");
batch.update(sfRef, {"population": 1000000});
// Delete the city 'LA'
var laRef = db.firestore.collection("cities").doc("LA");
batch.delete(laRef);
// Commit the batch
batch.commit().then(() => {
// ...
});
【讨论】:
很简单:
constructor(private db: AngularFirestore){}
inserting(){
//--create batch--
let batch = this.db.firestore.batch();
//--create a reference--
const userRef = this.db.collection('users').doc('women').ref;
batch.set(userRef , {
name: "Maria"
});
//--create a reference--
const userRef = this.db.collection('users').doc('men').ref;
batch.set(userRef , {
name: "Diego"
});
//--Others more 54 batch's--
//--finally--
return batch.commit();
}
【讨论】: