如何从从数据库(angular 6 和 firebase)检索数据的服务中为组件变量赋值?

How to assign value to a component variable from a service retrieving data from a database (angular 6 and firebase)?

我是 angular 编程的新手,问题当然很简单,但它让我抓狂!

我在 firestore 上有一个数据库,我正在使用服务从中检索数据。

数据由接口构成(嵌套其他接口,包括数组...)

我的服务:

@Injectable({
  providedIn: 'root'
})
export class InfogeneriqueServicesService {

  ItemsInfoGeneriqueCollection : AngularFirestoreDocument<Navigation>;

  Infogenes: Observable<Navigation>;   

  constructor(public afs: AngularFirestore) {

  this.ItemsInfoGeneriqueCollection = this.afs.doc('user/7878AZEVZAEV4'); 
  this.Infogenes = this.ItemsInfoGeneriqueCollection.valueChanges();

  } getInfoSGeneriques(){    
   return this.Infogenes;

}

我的组件 ts :

import {Navigation} from '../StructureInterfaces/structuresInter';
import { InfogeneriqueServicesService } from '../services/infogenerique-services.service';
...

Nav : Navigation;
...
constructor(private adapter: DateAdapter<any>, private NaviService : InfogeneriqueServicesService) {}

ngOnInit(){

     this.NaviService.getInfoSGeneriques().subscribe(IDperso =>{
    this.Nav = IDperso;

   });


   this.selectedgrade = this.Grades[this.Nav.id.grade-1].viewValue;

我得到一个错误:

ERROR TypeError: "this.Nav is undefined"

是不是因为此时this.Nav还没有生成? this.selectegrade... 指令是否应该等待生成数据(以及如何生成?)还是存在代码问题?

如有任何帮助,我将不胜感激...谢谢!

将设置 selectedGrade 的代码移到 getInfoSGeneriques 回调函数中,因为您正在执行的函数是异步的

ngOnInit(){
  this.NaviService.getInfoSGeneriques().subscribe(IDperso =>{
    this.Nav = IDperso;
    this.selectedgrade = this.Grades[this.Nav.id.grade-1].viewValue; 
  });
}