Soy nueva en angular y esas cosas.

A continuación se muestra el formato de la matriz que estoy obteniendo en la consola.

[]
0: {_id: "5b90fb38345c932d46e61dae", name: "Andhra Pradesh", abbvr: "AP"}
1: {_id: "5b90fb38345c932d46e61daf", name: "Arunachal Pradesh", abbvr: "AR"}
2: {_id: "5b90fb38345c932d46e61db1", name: "Bihar", abbvr: "BR"}
3: {_id: "5b90fb38345c932d46e61db6", name: "Gujarat", abbvr: "GJ"}
4: {_id: "5b90fb38345c932d46e61db3", name: "Chhattisgarh", abbvr: "CG"}
5: {_id: "5b90fb38345c932d46e61db8", name: "Himachal Pradesh", abbvr: "HP"}
6: {_id: "5b90fb38345c932d46e61dbb", name: "Karnataka", abbvr: "KA"}
7: {_id: "5b90fb38345c932d46e61dbd", name: "Madhya Pradesh", abbvr: "MP"}
8: {_id: "5b90fb38345c932d46e61dc0", name: "Odisha", abbvr: "OR"}
9: {_id: "5b90fb38345c932d46e61dc2", name: "Punjab", abbvr: "PB"}
10: {_id: "5b90fb38345c932d46e61dc5", name: "Tamil Nadu", abbvr: "TN"}
11: {_id: "5b90fb38345c932d46e61dc7", name: "Tripura", abbvr: "TR"}
12: {_id: "5b90fb38345c932d46e61dca", name: "West Bengal", abbvr: "WB"}
13: {_id: "5b90fb38345c932d46e61db2", name: "Chandigarh", abbvr: "CD"}
14: {_id: "5b90fb38345c932d46e61dcc", name: "Andaman and Nicobar Islands", abbvr: "AN"}
15: {_id: "5b90fb38345c932d46e61db7", name: "Haryana", abbvr: "HR"}
16: {_id: "5b90fb38345c932d46e61dbc", name: "Kerala", abbvr: "KL"}
17: {_id: "5b90fb38345c932d46e61dc1", name: "Puducherry", abbvr: "PY"}
18: {_id: "5b90fb38345c932d46e61dc6", name: "Telangana", abbvr: "TL"}
19: {_id: "5b90fb38345c932d46e61dcb", name: "Manipur", abbvr: "MN"}
20: {_id: "5b90fb38345c932d46e61db0", name: "Assam", abbvr: "AS"}
21: {_id: "5b90fb38345c932d46e61db4", name: "Delhi", abbvr: "DL"}
22: {_id: "5b90fb38345c932d46e61db9", name: "Jammu and Kashmir", abbvr: "JK"}
23: {_id: "5b90fb38345c932d46e61db5", name: "Goa", abbvr: "GA"}
24: {_id: "5b90fb38345c932d46e61dbe", name: "Maharashtra", abbvr: "MH"}
25: {_id: "5b90fb38345c932d46e61dc3", name: "Rajasthan", abbvr: "RJ"}
26: {_id: "5b90fb38345c932d46e61dba", name: "Jharkhand", abbvr: "JH"}
27: {_id: "5b90fb38345c932d46e61dbf", name: "Meghalaya", abbvr: "ML"}
28: {_id: "5b90fb38345c932d46e61dc8", name: "Uttar Pradesh", abbvr: "UP"}
29: {_id: "5b90fb38345c932d46e61dcd", name: "Mizoram", abbvr: "MZ"}
30: {_id: "5b90fb38345c932d46e61dc4", name: "Sikkim", abbvr: "SK"}
31: {_id: "5b90fb38345c932d46e61dc9", name: "Uttarakhand", abbvr: "UK"}
32: {_id: "5b90fb38345c932d46e61dce", name: "Nagaland", abbvr: "NL"}

Y HTML para el ngFor es:

<option  *ngFor="let state of states" [value]="state.name">{{state.name}}</option>

En la pantalla hay varias opciones, pero no hay nada visible cuando imprimo en la consola, se muestra indefinido

Edición 1: a continuación se muestra el código de los componentes que utilizan el servicio

import { Component, OnInit } from '@angular/core';
import {VenueService} from './venue.service';


@Component({
  selector: 'app-workshop',
  templateUrl: './workshop.component.html',
  styleUrls: ['./workshop.component.css']
})
export class WorkshopComponent  {
states=[];
  constructor(private venueService: VenueService) {

  }
  ngOnInit(){
   this.venueService.getStates().subscribe(state => {
     state.forEach(entry=>{
       this.states.push(entry);
     });
    });
    console.log(this.states);
  }

}  

Edición 2: estoy usando Observable durante la llamada API y la interfaz, por lo que este sería mi método de servicio:

getStates(): Observable<State[]>{
return http.get<State[]>('http://localhost:3000/api/getstate');
 }
2
Sharad Mishra 14 sep. 2018 a las 14:51

5 respuestas

La mejor respuesta

Si puede usar el Observable directamente desde su servicio, como sugiere su ejemplo, entonces la respuesta de Joseph Webber obtiene mi voto.

Sin embargo, si primero desea realizar algún procesamiento en el resultado, puede notificar a angular para detectar su cambio, llamando al detectChanges en el detector de cambio del componente.

Por ejemplo:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { VenueService } from './venue.service';

@Component({
  selector: 'app-workshop',
  templateUrl: './workshop.component.html',
  styleUrls: ['./workshop.component.css']
})
export class WorkshopComponent implements OnInit  {
  states = [];
  constructor(private venueService: VenueService,
    private changeDetector: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.venueService.getStates().subscribe(state => {
      // Do some stuff with the results ... 
      state.forEach(entry => {
        this.states.push(entry);
      });
      // Let angular know.
      this.changeDetector.detectChanges();
  });
  console.log(this.states);
 }
}
2
buzzwauld 14 sep. 2018 a las 14:10

venueService.getStates() es la función asynchronous.

Intente a continuación.

  ngOnInit(){
   this.venueService.getStates()
         .subscribe(state => {
             state.forEach(entry=>{
               this.states.push(entry);
           });
         console.log(this.states);
        });
  }
0
Sudarshana Dayananda 14 sep. 2018 a las 12:36

Debería mostrar una matriz vacía porque tiene un método asíncrono si desea mostrar una matriz después del método, debe usar aysnc / wait o asyn pip en html:

  async ngOnInit()
  {     const states= await                               
       this.venueService.getStates().toPromise();
        console.log(states);
  }
<option  *ngFor="let state of states" [value]="state.name">{{state.name}}</option>

Para la segunda forma:

Ya se mencionó en la primera respuesta

4
Soufiane Elmoudden 14 sep. 2018 a las 14:18

Use la canalización async en su HTML y configure states en el observable devuelto por su servicio.

<option *ngFor="let state of states | async" [value]="state.name">{{state.name}}</option>
ngOnInit(){
  this.states = this.venueService.getStates();
}
0
Joseph Webber 14 sep. 2018 a las 13:20

Intenta así,

<option  *ngFor="let state of states" [ngValue]="state">{{state.name}}</option>
0
Yuvaranjani 14 sep. 2018 a las 12:05