Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda