0

I have a related question (see link at the end) using Firestore with Angular 5:

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

This doesn't work in my code! I can see the correct docRef.id in the console.log(), but the postKey isn't accessible outside of the function when i add {{postKey}} to the html file - what am I doing wrong? =/

I tried the following:

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);
  };

But I either get an empty observable or i can't access the variable at all. x in this case is an observable, but i somehow need to extract the item docRef.id - simply using

this.myNeededDocrefId = x.docRef.id doesnt work!

Related question: Can I get the generated ID for a document created with batch().set using Firestore?

The author of the question says "you can easily get the id", but doesn't explain how.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

I've finally found the solution:

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