0

Пытаюсь получить данные из запроса с сервера ASP.Net и вывести их в выпадающий список на Angular 5/6.

Для этого создал класс:

export class Configuration
{
    public IdConfiguration: Number ;
    public ConfigurationLabel: String;
    public HotKey: String;
}

Класс сервиса, в котором выполняется запрос public getConfigurations() выглядит следующим образом:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Configuration } from '../classes/configuration';
import { catchError, map, tap } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class SortingService {
  public serverUrl = 'http://localhost:9000/api';
  msgBackend: Promise<string>;


  constructor(private http: HttpClient) {
   }

  public getConfigurations(): Observable<Configuration[]>{
    return this.http.get<Configuration[]>(this.serverUrl+"/configurations/get")
    .pipe(
      /*tap(batches => console.log(`fetched batch`)),*/
      catchError(this.handleError('getConfigurations', []))
    );
  }


  private handleData(data: any) {
    //console.log(data);
    this.msgBackend= data;
  } 


  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

}

Ну и собственно функция subscribe

 getConfigurations():void{
    /*this.configurations = [
      {IdConfiguration:1, ConfigurationLabel:"Яловка", HotKey:"a"},
      {IdConfiguration:2, ConfigurationLabel:"Бык", HotKey:"b"},
    ];*/
    this._sortingService.getConfigurations()   
    .subscribe(      
      configurations =>  this.configurations = configurations
    );

  }

Как видно я пробовал просто создать массив конфигурация и на странице все прекрасно работает в список выводится 2 значения "Яловка" и "Бык".

HTML:

<span>Конфигурация: </span>
    <select>
    <option *ngFor="let configuration of configurations" [ngValue]="configuration.ConfigurationId">{{configuration.ConfigurationLabel}}</option>
  </select>

С данными из запроса такого результата получить не удалось - поля пустые. Либо если вместо {{configuration.ConfigurationLabel}} написать {{configuration}} выдаст следующую картину: Object object

Сам запрос приходит в таком виде: Данные

Буду благодарен!

2
  • для начала посмотрите, что приходит в configuration.ConfigurationLabel {{configuration.ConfigurationLabel | json}}
    – StereoFlo
    30 мая 2018 в 15:10
  • а еще лучше в самом configuration - {{configuration | json}}
    – Dimanoid
    1 июн 2018 в 10:22

1 ответ 1

0

Необходимо привести к configurations типу Configurations[]

showConfigurations():void{
    this._sortingService.getConfigurations()   
    .subscribe((configurations: Configuration[]) => this.configurations = configurations);
  }

В самом же запросе необходимо передавать именно данные класса

export class Configuration
{
    public idConfiguration: number ;
    public configurationLabel: string;
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.