【问题标题】:Firestore get ref.id outside of the functionFirestore 在函数之外获取 ref.id
【发布时间】:2018-07-01 14:20:36
【问题描述】:

我有一个使用 Firestore 和 Angular 5 的相关问题(见最后的链接):

    db.collection('posts')
     .add({title: 'Hello World'})
     .then(function(docRef) {
       console.log('The auto-generated ID is', docRef.id)
       postKey = docRef.id
    });

这在我的代码中不起作用!我可以在 console.log() 中看到正确的 docRef.id,但是当我将 {{postKey}} 添加到 html 文件时,无法在函数之外访问 postKey - 我做错了什么? =/

我尝试了以下方法:

myFunction(a, b) {

    var postKey: string = "waiting";
    console.log(postKey);

    let x = this.db.collection('mydocs').add({
      a: a,
      b: b
    }).then(function(docRef) {
      console.log(docRef.id);
      postKey = JSON.stringify(docRef.id);
      return postKey;
    }).catch(function (error) {
      console.error("Error creating document: ", error);
    });

    console.log(postKey);
    this.x = postKey;
    console.log(x);
  };

但是我要么得到一个空的 observable,要么根本无法访问该变量。 x 在这种情况下是一个可观察的,但我需要以某种方式提取项目 docRef.id - 只需使用

this.myNeededDocrefId = x.docRef.id 不起作用!

相关问题:Can I get the generated ID for a document created with batch().set using Firestore?

问题的作者说“您可以轻松获取 id”,但没有解释如何。

【问题讨论】:

    标签: javascript promise observable google-cloud-firestore


    【解决方案1】:

    我终于找到了解决办法:

    x.then((value) => {
          console.log("Retrieved: ", value);
          this.myService.ID = value;
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2014-10-29
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多