Reputation: 1414
I'm trying to render a returned JSON from the backend in to HTML {{ object.x }}
, I'm using BehaviourSubject
in my shared-service where I call the API endpoint of the list I'm trying to render.
public storesChanged = new BehaviorSubject([]);
public getStores(): void {
this.retrieveResults().subscribe((results) => {
this.storesChanged.next(results.Results)
console.log('Name >> ', results.Results[0].Name) // this shows me the Name
});
}
public retrieveResults(): Observable<any> {
return this.http.get('/api/Stores/Summary')
.map(res => res.json())
}
using this service:
this.sharedService.storesChanged.subscribe((res) => {
this.currentStore = res.find((x) => x.Id === this.storeId)
// this returns the object based on the Id which should be able to use in my HTML
})
This is the object which I'm trying to render in HTML {{ currentStore.Name }}
however it's returning an error Cannot read property 'Name' of undefined
.
{
'Id': 1,
'Name': 'Eastleigh'
}
I'm quite confused why its returning 'Name' of undefined
when the property is in the object. Can someone point-out the cause.
Upvotes: 2
Views: 364
Reputation: 40647
Since your currentStore
object is received asynchronously, you can use the "elvis" operator like this
{{ currentStore?.Name }}
"elvis" or safe navigation operator will check your object if it's null/undefined or not. And when it's defined, angular will try to access the property you have selected (Name).
Source: https://en.wikipedia.org/wiki/Safe_navigation_operator
Upvotes: 1