简体   繁体   中英

how do I get a single value from firebase using angularfire2 and angular5?

I am trying to obtain and display a single value from firebase.

My firebase structure looks like this: 在此处输入图片说明

My current .ts file looks like:

storestat$: Observable<any[]>;

constructor(afDb: AngularFireDatabase) {
     this.storestat$ = afDb.list<any>('MyShop').snapshotChanges();
}

I want to display the storeStatus value within the html using {{}} binding. Something like the following:

<button>{{ storeStatus }} Status</button>

I tried using the following initially:

<ng-container *ngFor="let s of storestat$ | async">...
<button>{{ s.storeStatus }}</button>

but of course that wouldn't work.

I tried searching for answers but they just didn't seem quite relevant as they were all pointing to obtaining multiple specific values from lists.

I am using angularfire2 and angular5.

I am new to angular5 so any help would be appreciated, including any educational pointers.

I have a workaround but not sure if it is the best solution. my new .ts file relevant portion looks like:

    this.storestat$ = afDb.list<any>('myshop').snapshotChanges()
       .map(
            changes => {
               return changes.map(
                  c => ({ val: c.payload.val(), 
                          key: c.payload.key,
                          ...c.payload.val()
                   })
               );
       });

and my .html relevant portion now looks like:

<ng-container *ngFor="let s of storestat$ | async">

  <button *ngIf="s.key == 'storeStatus'">{{ s.val }} Status</button>

</ng-container>

I don't think this is the cleanest solution as the database call maps the unwanted Current Orders branch as well, but it works.

If you are not care about the push keys you can use .valueChanges() and it should work like this

afDb.list<any>('myshop').valueChanges().subscribe(value => 
{
    this.storestat$ = value;
});

and in html

<ng-container *ngFor="let s of storestat$">

  <button>{{ s.storeStatus }} Status</button>

</ng-container>

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