在firestore中的angularfire2交易和批量写入 [英] angularfire2 transactions and batch writes in firestore

查看:88
本文介绍了在firestore中的angularfire2交易和批量写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在angular2应用中使用Firestore批量写入/运行事务?

How can I do batch writes/run transactions with firestore in an angular2 app?

https://firebase.google.com/docs/firestore/manage-数据/交易

如果可能的话,如何在angular2应用中将JS代码转换为TS代码.

If it's possible, how can I convert the JS code to TS code in an angular2 app.

推荐答案

如果您使用的是AngularFirestore,则首先需要确保您的构造函数的设置如下:

If you are using AngularFirestore, firstly you will need to make sure that your constructor is setup as follows:

constructor(private db: AngularFirestore)

现在,您可以使用db.firestore来获取firebase.firestore实例.

Now you can use db.firestore to get a firebase.firestore instance.

您只需复制链接中的代码,然后将 db 替换为 db.firestore .或者,您也可以使用箭头功能使其更加精美:

You can just copy the code from the link and replace db with db.firestore. Or you can make it more fancy using arrow functions:

通过事务更新数据:

// 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(() => {
    // ...
});

这篇关于在firestore中的angularfire2交易和批量写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆