Alan ENTEM
Alan ENTEM

Reputation: 129

Angular 7 Extract data from observable

I am new in angular.

i want extract data from an observable. i do that :

validnomi(key : string): void {
  this.demandesnomiftodisplay = 
    this.demandenomisService.getSingleDemandenomis(key).subscribe(val => 

    {const civ = val[0].civ; 
     const datedemande = val[0].datedemande; 
     const nom = val[0].nom; 
     const prenom = val[0].prenom; 

     }
  );
}

my service.ts :

getSingleDemandenomis(key: string){
return this.database.list('/Demandes/DemandesBALnominatives', ref => ref.orderByKey().equalTo(key)).snapshotChanges().pipe(map(actions => {
  return actions.map(a => {
    const data = a.payload.val();
    const key = a.payload.key;
    return {key, ...data };
  });
}));
 }

But i have this error :

property prenom does not exist on type {key : string}
property nom does not exist on type {key : string}
property civdoes not exist on type {key : string}

....

Upvotes: 1

Views: 4243

Answers (3)

Borys Kupar
Borys Kupar

Reputation: 1721

It looks correct, you just need further to read first element of array and access needed property.

Your service:

getSingleDemandenomis(key: string): Observable<{key: string; datedemande: string}[]> {
   return this.database.list('/Demandes/DemandesBALnominatives', ref => 
       ref.orderByKey().equalTo(key)).snapshotChanges().pipe(map(actions => {
          return actions.map(a => {
              const data = a.payload.val();
              const payloadKey = a.payload.key;
              return {key: payloadKey, ...data };
          });
   }));
 }

Component:

validnomi(key : string) {
    this.demandesnomiftodisplay = this.demandenomisService.getSingleDemandenomis(key)
    .subscribe((val: {datedemande: string}[]) => console.log(val[0].datedemande));
}

Upvotes: 2

thomi
thomi

Reputation: 1687

I would stick to the observable:

validnomi(key : string) {
  this.demandesnomiftodisplay = 
    this.demandenomisService.getSingleDemandenomis(key).pipe(
    pluck('datademande')
  ).subscribe(val => console.log(val));

Here's a StackBlitz to illustrate.

Upvotes: 1

Antoine Delia
Antoine Delia

Reputation: 1845

The brackets from your log indicates that you are not getting an object but rather an array of object. Just get the first element of the array and then you will be able to access all the attributes of your object.

Also, you should not use JSON.stringify(), as it turns your array of object into a string.

validnomi(key : string) {
    this.demandesnomiftodisplay = this.demandenomisService.getSingleDemandenomis(key).subscribe(val => 
        // This will get the key from your object
        console.log(val[0].key);
    );
}

Upvotes: 1

Related Questions