Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
Angular: Trying to get an Object from an Array by index, but i got an undefined error

When the page loads it gets the countries from my rest api and when a user choose a country it loads the cities for the country. It works fine so far but when the page is opened, the city is empty beacuse it only gets the citeies when the user at least once choose a country (the (change) event).

To avoid this i want to gets the first element of the countries[] and load the cities with the country id in ngInit.

But it always undefined if i want to get an elemnt from the countries array. I tried multiple ways but i can't get it to work.

Country Model:


export interface Country{
    id: number;
    name: string;
}

Component.ts:

countries: Country[] = [];
  cities : City[] = [];
  
  loading: boolean = false;
  errorMessage: string | undefined;


  constructor(
    private countryService: CountryServiceService,
    private cityService: CityService) { 

    }

  ngOnInit(): void {
    this.getCountries(); 
    console.log(this.countries[0]);

  }

getCountries()

   public getCountries(){
    this.countryService.getCountries().subscribe( response => {
      this.countries = response;
     }
    )
   }

HTML:

<select (change)="getCities($event)">
            <option *ngFor="let country of countries"
             [value]="country.id">
             {{country.name}}
            </option>
        </select>

        <select>
            <option *ngFor="let city of cities"
            [value]="city.id">
            {{city.name}}
          </select>
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

There is many ways to do this. but in your way that you want. you can try below.

and I believe you have getCities(countryId:number) method. so just do this.

public getCountries(){
    this.countryService.getCountries().subscribe( response => {
      this.countries = response;
      this.fillCities(this.countries[0].id);
     }
    
   }

fillCities(id:number){
    this.cityService.getCities(id).subscribe( response => {
     this.cities=response;
     }
}

you need to handle type checks/ validations. Above code is straight forward as per your requirement.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda