簡體   English   中英

Angular 7提取可觀察數據

[英]Angular 7 Extract data from observable

我是新手。

我想從可觀察的數據中提取數據。 我這樣做:

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; 

     }
  );
}

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

但是我有這個錯誤:

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}

....

看起來正確,您只需要進一步閱讀數組的第一個元素並訪問所需的屬性即可。

您的服務:

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

零件:

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

日志中的括號表示您不是在獲取對象,而是在獲取對象數組。 只需獲取數組的第一個元素,便可以訪問對象的所有屬性。

另外,您不應使用JSON.stringify() ,因為它將對象數組轉換為字符串。

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

我會堅持觀察:

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

這是一個StackBlitz來說明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM