Search code examples
angularservicereal-timelifecycle

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


I'm new in angular programming and the question is surely simple but it drinving me crazy!

I have a database on firestore and i'm retrieving datas from it with a service.

The datas are structured with interfaces (nesting other interfaces including array...)

My service :

@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;

}

My component 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;

and i get an error :

ERROR TypeError: "this.Nav is undefined"

Is it because the this.Nav is still not generated at this point ? Should this.selectegrade... instruction wait for the data to be generated (and how ?) or is there a code issues ?

I would be gratefull for any help... Thanks !


Solution

  • Move the code for setting the selectedGrade inside getInfoSGeneriques callback function, because the function you are executing is asynchronous

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