1

I have a problem with an array that is supposed to be empty, the problem is that it is not, and it has an undefined element inside so it does not allow me to query the backend correctly.

this is the component with problem and the console log:

export class AvailabilityVerifierComponent implements OnInit {

  usersAvailabilities: UserAvailability[] = [];

  users: Array<User> = [];

  @Input() 
  set userToVerify(user: User){
    console.log('users array in input');
    console.log(this.users);
    console.log('User en AvailabilityVerifierComponent');
    console.log(user);
    console.log('users componente after push ');
    console.log(this.users);
    this.users.push(user);    
    console.log('users componente before push ');
    console.log(this.users);
    this.verifyAvailabilitiesService.verify(this.users)
    .subscribe(
      response => {
        this.usersAvailabilities = response;
      },
      error => {
        console.log(error);
      }  
    );

  }

  constructor(
    private verifyAvailabilitiesService: VerifyAvailabilitiesService
  ) { }

  ngOnInit() {
  }
}

enter image description here

2
  • 2
    change users: Array<User> = [] in users: User[]; in the onInit -> this.users = []; and do a console.log(this.user). Is empty? Commented Nov 21, 2018 at 15:37
  • now is empty, cool. but angular now it shows me an error when executing the input function because it can not use the .push method in undefined. After I add a user this is solved, but before that the error is present. Commented Nov 21, 2018 at 15:45

1 Answer 1

4

Your console log sadly changes over time; it gets revaluated. There is no way your initial array has one undefined element in it. What happens here is that when your component is initialized, the input is called with undefined as a parameter. Thus you push "undefined" into your array. Change the this.users.push(user) into

if (user) { 
   this.users.push(user); 
}

and you should be all set; except your server will be called twice. You might just want to add:

if (!user) {
   return;
}

to the top of your userToVerify method.

Sign up to request clarification or add additional context in comments.

1 Comment

this has solved the problem correctly, thank you very much for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.