简体   繁体   中英

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}

....

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));
}

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);
    );
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM