Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
Angular: intento obtener un objeto de una matriz por índice, pero obtuve un error indefinido

Cuando la página se carga, obtiene los países de mi API de descanso y cuando un usuario elige un país, carga las ciudades del país. Funciona bien hasta ahora, pero cuando se abre la página, la ciudad está vacía porque solo obtiene las ciudades cuando el usuario elige un país al menos una vez (el evento (cambiar)).

Para evitar esto, quiero obtener el primer elemento de los países [] y cargar las ciudades con la identificación del país en ngInit.

Pero siempre está indefinido si quiero obtener un elemento de la matriz de países. Intenté de varias maneras pero no puedo hacerlo funcionar.

Modelo de país:

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

Componente.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]); }

obtenerPaíses()

 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 answers
Answer question

0

Hay muchas maneras de hacer esto. pero a tu manera que tu quieras. puedes probar a continuación.

y creo que tiene getCities(countryId:number) . así que solo haz esto.

 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; } }

necesita manejar comprobaciones/validaciones de tipo. El código anterior es sencillo según sus requisitos.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!