quimak
quimak

Reputation: 125

TypeScript array methods not working

I am wrestling with some serious issues. I was trying to use in my code several array methods like push, includes, filter. None of them works.
ERROR TypeError: Cannot read property 'push' of undefined

Simple use of push:

  users: User[];
  user = new User('','','','','','','','','');

  addUser(user){
    this.usersService.addUser(user)
    .subscribe(
      user => this.users.push(user),
      error => this.errMsg = <any> error);
  } 

UPDATE: Accidentally commented out initialization of Users.

this.getUsers();  

if(this.users.find(this.checkLogin) === undefined){
  console.log('OK no login like this');
}else{
  console.log('Login like this exists');
}
checkLogin(element){
  return element === this.user.login;
}

getUsers(){
  this.usersService.getUsers()
  .subscribe(
    users => this.users = users,
    error => this.errMsg = <any> error);
}

Still getting error:
ERROR TypeError: Cannot read property 'find' of undefined

Upvotes: 0

Views: 3102

Answers (1)

Reactgular
Reactgular

Reputation: 54781

Change:

 users: User[];

To:

  users: User[] = [];

Upvotes: 4

Related Questions