M
M
Maxim2017-10-31 12:07:52
Angular
Maxim, 2017-10-31 12:07:52

Angular Get request/form validation?

Hello!
There is a Get request

server.services.ts
getStations(){
    return this.http.get('http://62.141.52.96/site/act.php?action=getstations')
    .map(
      (response: Response) => {
        const data = response.json();
        return data;
      }
    );
  }


I call in
app.components.ts
ngOnInit(){
    this.serverService.getStations()
        .subscribe(
          (data: any[]) => console.log(data),
          (error) => console.log(error)
     );
  }


I get, respectively, in the console
console
(3) [{…}, {…}, {…}]
           0: 
                      city: "Kiev"
                      id_city: "694"
           1: 
                      city: "Moscow"
                      id_city: "825"
           2: 
                      city: "New York"
                      id_city: "429"

1. What is the correct way to iterate through the array in Angular and take only the city value?
I do it out of habit
for(var i=0;i<data.length;i++){
            console.log (data[i].city)
          };

2. There is an input in the form in which I check the entered value
app.component.ts
Stations = ['Moscow',  'Kiev'];
ngOnInit() {
this.signupForm = new FormGroup({
         'inputFrom' : new FormControl(null, [Validators.required, this.rightStations.bind(this)]),
}

  rightStations (control: FormControl): {[s: string]: boolean}{
    if (this.Stations.indexOf(control.value) ==-1){
      return {'rightStationsIs': true};
    }
    return null;
  }


Now I want to redo it in order to get the value of cities from the Get-request and check them with the entered values ​​and, by clicking Submit, send the ID of the entered city to the server.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wondergrauf, 2017-11-01
@Wondergrauf

1. There is a .map() method that iterates over the elements of an array:

ngOnInit(){
    this.serverService.getStations()
        .subscribe(
          (data: any[]) => {
            console.log(data.map((item) => item.city)
            this.stations = data.map((item) => item.city)
          }),
          (error) => console.log(error)
     );
  }

2. The validator will look something like this:
rightStations (control: FormControl): {[s: string]: any}{
  return this.Stations.indexOf(control.value) !== -1 ? {'rightStationsIs': true} : null
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question