Search code examples
javascriptangulartypescriptobservable

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.


Solution

  • If getUsers() is an Observable, you can try this. users doesn't have to be an Observable.

    reloadData() {
        this.UserService.getUsers().pipe(take(1))
          .subscribe((users: any) => {
            this.users = users;
          });
        console.log(this.users)
        this.getTotalEmplyees();
      }
    

    If getUsers() is not an Observable, then users shouldn't be an Observable either