Mohamed Ali Lassoued
Mohamed Ali Lassoued

Reputation: 311

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.

Upvotes: 4

Views: 5603

Answers (4)

Pung Worathiti Manosroi
Pung Worathiti Manosroi

Reputation: 1490

If you need to check the length in the *ngIf directive, you can do something like this

<div *ngIf="(users | async).length > 0">
  
</div>

Upvotes: 1

Radim Šafr&#225;n
Radim Šafr&#225;n

Reputation: 598

In .ts file:

let isUser: boolean = (await this.getUsers().toPromise()).length > 0; 

Or

in template:

<div *ngIf="(getUsers() | async).length > 0">
...Users
</div>

Upvotes: 0

Adrian Brand
Adrian Brand

Reputation: 21638

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.

Upvotes: 5

zer0
zer0

Reputation: 5017

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

Upvotes: 2

Related Questions