skip to Main Content

the problem is that the console represent ‘undefined’.

this.firestore.collection('list').doc('1').get().subscribe((doc: any) => {
   this.myAns = doc.data().answer ? doc.data().answer : "no answer";
});

console.log('this.myAns', this.myAns);

but, I want to get right answer in console.

this.firestore.collection('list').doc('1').get().subscribe(async (doc: any) => {
   this.myAns = await doc.data().answer ? doc.data().answer : "no answer";
});

console.log('this.myAns', this.myAns);

i tried this one. but not working.

this.firestore.collection('list').doc('1').get().subscribe((doc: any) => {
   this.myAns = doc.data().answer ? doc.data().answer : "no answer";
   console.log('this.myAns', this.myAns);
});

i know this works well, but what I want is represent outside of this.firestore.
please, help me..

2

Answers


  1. You should this.myAns inside the subscribe block. If you need to use this.myAns outside of the subscribe block, you can trigger the necessary logic from within the subscribe block or use a callback function.

    
    fetchAnswer() {
      this.firestore.collection('list').doc('1').get().subscribe((doc: any) => {
        this.myAns = doc.exists ? doc.data().answer : "no answer";
        console.log('this.myAns inside subscribe', this.myAns);
        this.handleAnswer(this.myAns);
      });
    }
    
    handleAnswer(answer: any) {
      console.log('this.myAns outside subscribe', answer);
    }
    
    Login or Signup to reply.
  2. The Firebase API supports this out-of-the-box (see documentation, "Get a document"):

    import { initializeApp } from "firebase/app";
    import { getFirestore, doc, getDoc } from "firebase/firestore";
    
    const firebaseConfig = {
      // ...
    };
    
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);
    
    const docRef = doc(db, "list", "1");
    const docSnap = await getDoc(docRef);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search