简体   繁体   English

Angular 7提取可观察数据

[英]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 : 我的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. 另外,您不应使用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);
    );
}

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. 这是一个StackBlitz来说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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