Fill select in Angular with API query results

1

I'm making an application with Angular 4 and using Materialize CSS. My goal is: when a certain component is loaded, an HTTP query is made that extracts some data, which will dynamically fill a select content in the view. Next, I show the service that makes the query:

import { Injectable } from '@angular/core';
import { Http, Response, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable} from 'rxjs/Observable';


@Injectable()
export class citasService{

    public url:string;

    constructor(private _http:Http){
       this.url = "URL API";
    }

    getCenTra(){
        return this._http.get(this.url)
        .map(res => res.json());
    }
}

This service is injected into the component, and the search is performed successfully with the method ngOnInit() . The code is shown below:

import { Component } from '@angular/core';
import { citasService } from '../services/citas.service';
import { CitasModel } from './citas.model';

declare var $:any;
declare var Jquery:any;

@Component({
  selector: 'citas',
  templateUrl: './citas.component.html',
  styleUrls: ['./citas.component.css'],
  providers: [ citasService ]

})
export class citasComponent {

  public datos_Cen_Tra: CitasModel;

  constructor(private _resultado:citasService){
    this.datos_Cen_Tra = new CitasModel("",0,"","",0,"", "");
  }

  ngOnInit(){
    $('select').material_select('destroy');
    this._resultado.getCenTra().subscribe(
      result=>{
         if(result.count == 1){
           this.datos_Cen_Tra = result.cen_tra[0];
           $('select').material_select();
         }else{
          console.log(result);
         }
      },
      error=>{
        var errorMessage = <any>error;
        console.log(errorMessage);
      }
    );
  }

And then the html where the result is printed:

<div class="input-field col s12">
    <select id="listCenTra">
      <option value="">{{datos_Cen_Tra.name_com}}</option>
    </select>
    <label>Seleccione centro de trabajo</label>
</div>

The problem is that, the data does not get loaded in the select:

On the other hand, if I print it on the screen, for example inside a p-label, if it is printed correctly:

<p>{{datos_Cen_Tra.id}}</p>

I do not know what may be failing. Thank you in advance for the help.

    
asked by AntonioMP87 16.12.2017 в 19:12
source

2 answers

1

Try the following option, iterate over your result with an * ngFor in. From what I understand you have a list of work centers, so iterating over it and showing the results would be feasible.

Then I leave you as the html would be. I hope you find it useful.

<div class="input-field col s12">
            <select id="listCenTra">
              <option value="" *ngFor="let dato of datos_Cen_Tra">
                 {{dato.name_com}}
             </option>
            </select>
            <label>Seleccione centro de trabajo</label>
    </div>
    
answered by 18.12.2017 / 12:42
source
0

Thank you very much for all the help. In the end I did not manage to parse the http response by the JSON.parse method, although in fact, the problem was that the response was not stored in the form of an array. In the end, what I did was store the response in a variable created as an array public resultadoConcepto:Array<any>;

and then go through this variable in the ngFor:

<select id="listConcep">
          <option value=""  *ngFor = "let concepto of resultadoConcepto;">{{concepto.name}}</option>
        </select>
        <label>Seleccione concepto</label>

In this way, the drop-down is filled with the extracted data.

    
answered by 01.01.2018 в 16:17