Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

getting undefined result when using get function on cloud Firestore in Firebase using Angular

I'm pretty new in Angular. I'm trying to use a get function to return the data in my cloud firestore database in firebase. The response I'm getting is undefined, even though as you can see from the image below, there is definitely data in there. I think maybe the problem is my subscribe function in the component. I've tried many different way, but it's not working.

this is my code: in service

 constructor(private afs: AngularFirestore, private aff: AngularFireFunctions) {}

 getConfigurations() {
    return this.afs.collection<Configuration>('configurations').valueChanges()  }

in my ts file

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection} from "@angular/fire/firestore";
import {AngularFireFunctions} from "@angular/fire/functions";
import {Configuration} from "../../dashboard/dashboard.service";
import {DashboardService} from "../../dashboard/dashboard.service";

@Component({
  templateUrl: './vaccine-codes.component.html',
  styleUrls: ['./vaccine-codes.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class VaccineCodesComponent implements OnInit {

  configurations$: Configuration[];

constructor(private dashboardService: DashboardService) {

}
  // configurations$ = this.dashboardService.getConfigurations()

  getConfigurations() {
    this.dashboardService
      .getConfigurations()
      .subscribe(res => (this.configurations$ = res)

      );
    console.log(this.configurations$);

  }

  ngOnInit(): void {
    this.getConfigurations();
  
  }


}

these are my classes/interfaces:


export interface Configuration {
  ChpPrefix: string;
  Vaccines: { [key: string]: Vaccine[] };
  description: string;

}

export interface Vaccine {
  Codes: string[] | null;
}

this is my database: enter image description here

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your getConfigurations asynchronously get data. When you call console.log(this.configurations$) just after the function, the data still not received.

You have to check response inside subscribe.

  configurations$: Configuration[]; 
  getConfigurations = () =>
    this.dashboardService
      .getConfigurations()
    .subscribe(res => {
      this.configurations$ = res;
      console.log(this.configurations$);
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...