2

I need to get the values that are inside cities from this JSON, but i can´t:

{ 
"id":0,
"department":"Amazonas",
"cities":["Leticia","Puerto Bayarta",]
},
{ 
"id":1,
"department":"Antioquia",
"cities":["Medellin","Bello",]
}

These are the components and services that I made:

cities.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CitiesService {
  constructor(private http: HttpClient) {}
  getJSON(url: string) {
    return this.http.get(url);
  }
}

Component has an interface:

nueva-organizacion.component.ts

import { Component, OnInit } from '@angular/core';

import { CitiesService } from 'src/app/services/cities.service';

interface City{
  department: string;
  cities: string[];
}

@Component({
  selector: 'app-nueva-organizacion',
  templateUrl: './nueva-organizacion.component.html',
  styleUrls: ['./nueva-organizacion.component.css'],
})
export class NuevaOrganizacionComponent implements OnInit {
  public cities: City[] = [];
  constructor(
    public cities: CitiesService,
  ) {}

  ngOnInit(): void {
    this.cities
      .getJSON(
        'https://raw.githubusercontent.com/marcovega/colombia-json/master/colombia.min.json'
      )
      .subscribe((res: any) => {
        this.cities = res;
      });
  }

And finally, i would like to show the cities in a selector:

nueva-organizacion.component.html

<div class="form-input">
   <select id="city" class="custom-select">
      <option selected>Choose one...</option>
      <option *ngFor="let city of cities">
         {{ city.cities }}
      </option>
   </select>
</div>

I would like to get something like this in the selector:

Choose one...
Leticia
Puerto Bayarta
Medellin
Bello

But I get this:

Choose one...
Leticia, Puerto Bayarta
Medellin, Bello

Maybe the correct way is using the index {{ city.cities[] }} but I don't know how.

2 Answers 2

2

Please keep in mind that inside NuevaOrganizacionComponent you have to properties with the same name: 'cities', first the cities array and second the cities service.

Also I recommend you to use two selects instead of one, the first to select the department and the second to select the city.

The code will look like this:

nueva-organizacion.component.ts:

import { Component, OnInit } from '@angular/core';
import { CitiesService } from 'src/app/services/cities.service';

@Component({
  selector: 'app-nueva-organizacion',
  templateUrl: './nueva-organizacion.component.html',
  styleUrls: ['./nueva-organizacion.component.css'],
})
export class NuevaOrganizacionComponent implements OnInit {
  public departmentsArr = [] 
  public departmentSelected:any = null;
  public citySelected:any = null;
  constructor(
    public citiesServ: CitiesService,
  ) {}

  ngOnInit(): void {
    const urlCities = "https://raw.githubusercontent.com/marcovega/colombia-json/master/colombia.min.json"
    this.citiesServ.getJSON(urlCities)
    .subscribe((res: any) => {
        this.departmentsArr = res;
    });
  }
  getCities(){
      return this.departmentsArr.find(department => department.id == this.departmentSelected).ciudades
  }
  alertSelection(){
      const departmentName = this.departmentsArr.find(department => department.id == this.departmentSelected).departamento;
      const cityName = this.citySelected;
      alert(`
      You selected the department: ${departmentName} and the city: ${cityName}`)
  }
}

nueva-organizacion.component.html

<div class="form-input">
    <label for="departmentSelector">Select your department</label>
   <select id="departmentSelected" class="custom-select" name="departmentSelector" [(ngModel)]="departmentSelected">
      <option value="null">Choose one department...</option>
      <option 
        *ngFor="let department of departmentsArr"
        [value]="department.id">
         {{ department.departamento }}
      </option>
   </select>
</div>

<div class="form-input" *ngIf="departmentSelected">
    <label for="citySelector">Select your city</label>
    <select id="citySelector" class="custom-select" name="citySelector"  [(ngModel)]="citySelected">
      <option selected>Choose one city...</option>
      <option 
        *ngFor="let city of getCities()"
        [value]="city">
         {{ city }}
      </option>
   </select>
</div>

<button (click)="alertSelection()">WHAT WAS SELECTED?</button>

Also please verify FormsModule is imported into your app.module.ts or yourSubmodule.module.ts. This is important to enable the ([ngModule]) functionality.

import {FormsModule} from "@angular/forms";
// Other things
imports: [
    // Other modules
    FormsModule
  ],

Sign up to request clarification or add additional context in comments.

Comments

0
ngOnInit(): void {
  this.cities
    .getJSON(
      'https://raw.githubusercontent.com/marcovega/colombia-json/master/colombia.min.json'
    )
    .subscribe((res: any) => {
      this.cities = [];
      foreach(entry in res){
        foreach(citi in entry.cities){
          this.cities.push(citi);
        }
      }
    });
}

On this side, you have an array of entries that has an array of cities inside. You need to flatten first all the cities inside ans, something like the code above. My code isn't exact but should give you an idea of what to write.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.