简体   繁体   中英

Array adds undefined element, angular 6

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() {
  }
}

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM