Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length property does not exist with observables

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.

like image 860
Mohamed Ali Lassoued Avatar asked Sep 02 '25 09:09

Mohamed Ali Lassoued


1 Answers

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.

like image 121
Adrian Brand Avatar answered Sep 04 '25 21:09

Adrian Brand