简体   繁体   中英

How to declare a variable with a return method as value in Angular?

I am using [ngModel] to save the value of a selected option on Angular, but the default value has to be an existing option I can retrieve with this method

getPersonnageByIdd(id: string) {
    const persoSelectionne = this.personnages.find((x: { id: string; }) => x.id === id);
    return persoSelectionne;
  }

The problem is if I declare a variable with the return of that method as value like so

persoDefault = this.getPersonnageByIdd("demochar").name;

The whole component crashes, I have not found an answer for this after a good deal of research. please help, Regards,

I can put the method directly in [ngModel] and the default works, but I need to keep track of the selected option and I would need a variable to do so.

I guess this.personnages does not have the element demochar . In this case, find and getPersonnageByIdd returns undefined .

One solution is to use optional chaining.

persoDefault = this.getPersonnageByIdd("demochar")?.name;

From the code you have provided, there is no attribute called "name" in the result provided by getPersonnageByIdd().

This is how I would go about it

// Assuming that the current component has all the people loaded into an array called peopleList. You want to return the age of the Person which you have found by their id.
getPersonAgeById(id: number) {
    Person foundPerson = this.peopleList.find(x => x.id === id)
    return foundPerson.age; // also assuming that the Person object has an attribute called age of with the type number.
}

Also some suggestions:

  • Proper naming for classes, functions, variables is quite important to be able to keep track of everything.
  • It is unusual to use a string for "id"s (Although in this case it is hard to make a judgment based on the amount of code you provided. Feel free to share the accompanying classes with us)

As pointed by a few of you, the problem came from the fact there was no attribute called "name" in the result provided by getPersonnageByIdd(), because I needed to change my API request; the object returned by this call to an API didn't contain all the informations needed. Thank you all for pointing me in the right direction

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