I want to make a total for my users and display it but i get this issue
[ts] Proprety 'length' does not exist on type 'Observable User'. [2339]
this is my ts file
users: Observable<User[]>;
totalEmplyees:number;
constructor(private UserService: UsersService) { }
ngOnInit() {
this.reloadData();
}
reloadData() {
this.users = this.UserService.getUsers();
console.log(this.users)
this.getTotalEmplyees();
}
getTotalEmplyees(){
let total = 0 ;
for (let index = 0; index < this.users.length; index++) {
total += 1 ;
}
this.totalEmplyees = total;
console.log(this.totalEmplyees);
}
i hope that somone suggest for me a solution for this issue.
Your service is returning an Observable, you should use the convention to end Observable names with a $. Then you should use the async pipe in your template to subscribe to users$.
users$: Observable<User[]>;
constructor(private UserService: UsersService) { }
ngOnInit() {
this.users$ = this.UserService.getUsers();
}
and in your template you can assign the subscription to a view variable called users and just access the length peoperty to get how many there are.
<div *ngIf="users$ | async as users">
There are this many users: {{users.length}}
</div>
Here we have used the async pipe to subscribe to the observable and assign the array to a view variable called users. It is best to manage subscriptions to Observables this way in the template rather than in the TypeScript and have to worry about unsubscribing.
Looping through an array to count how many there are is unnecessary as that is what the length property of the array already is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With