简体   繁体   中英

How to show TypeScript object in HTML (Ionic/Firebase/Angular)

How do I display an object in my HTML file? (Using Ionic) It seems fairly simple, but it won't work. I retrieve the object like this, from a snapshot of my database path:

this.userPath.subscribe(snapshots => {
  this.snapshotValue = snapshots.val()
  console.log(this.snapshotValue);
})  

And the console looks something like this:

http://i.imgur.com/Kk0A6n5.png (I don't have 'reputation' to post images)

I feel like I've tried everything. Like:

<h1>{{snapshotValue}}</h1>  //this returns "[object object]"
<h1>{{snapshotValue.navn}}</h1>  //this gives me an error: "cannot read property navn of undefined"
<h1>{{snapshotValue[0]}}</h1>   //this gives me an error: "cannot read property '0' of undefined.

How do I get the individual values from this object?

This happens when you try to render the view before the data is available.Try the following method

In your component declare a boolean variable

private isDataAvailable:boolean=false;

And in your subscribe method make this true once the data is available

this.userPath.subscribe(snapshots => {
  this.snapshotValue = snapshots.val()
  console.log(this.snapshotValue);
  this.isDataAvailable=true;
}) 

And reneder the template once the data is available using *ngIf

<div *ngIf="isDataAvailable">
    <h1>{{snapshotValue}}</h1>  
    <h1>{{snapshotValue.navn}}</h1>  
    <h1>{{snapshotValue[0]}}</h1>   
</div>

This should do the trick.You can also use async pipe for the same.Find docs here

<h1>{{snapshotValue | json}}</h1> // this should return you a { stringified json }

you want to use the async pipe with the elvis operator (?) for observables. Below is using just the elvis.

<h1>{{snapshotValue?.navn}}</h1>

The elvis operator checks if the object exists before checking for a property on the object.

In the future instead of using this

this.userPath.subscribe(snapshots => {
  this.snapshotValue = snapshots.val()
  console.log(this.snapshotValue);
})

you can do

<h1>{{(userPath | async)?.navn}}</h1>

https://angular.io/api/common/AsyncPipe The async pipe does the subscribe and gets the latest value for you

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