I have a DashboardComponent
that will display certain general data to the user. One such point of data is the number of Users we have on board.
I also have a UserService
which has a method called getUsers()
which returns JSON-mapped HTML response. So, in DashboardComponent
I subscribe to this response:
this._uService.getUsers()
.subscribe(
users => this.users,
error => alert(error)
)
So now all I have to do is to display the length of this array in the DOM, with something like
We have {{users.length}} users on board!
(Or create a variable in DashboardComponent
called companyCount
and equate it to the users
array length.)
The problem here is, when I do so, it tells me that users is as of yet undefined. Which is understandable as it's an observable and when it's trying to access it, it's not there. But I am not quite sure about the solution.
To me, the odd thing is that even if {{users.length}} (or even {{users[0]}}) gives an error, I can still use *ngFor #user of users, and display all the users nicely in a table, and it won't give me an error.
I found a way around, even though it's not what I want. I never actually get the users array but do this instead:
this._uService.getUsers()
.subscribe(
users => this.userCount = user.length,
error => alert(error)
)
and then in the template
<div *ngIf="userCount">We have {{userCount}} users on board!!</div>
So this div isn't displayed until the userCount is defined, meaning the subscription data has become available.
This does not look like a good solution to me, especially since on the dashboard I will eventually need to display stats with more complex calculations, tables etc.
What is the general approach to tackling this problem?