首页 > 解决方案 > angular 8 populate 从 observable 下拉

问题描述

我是 Angular 的新手,并试图从 Angular 8 中的 observable 填充下拉列表,但没有得到任何乐趣。当我将数据写入控制台日志时,我可以看到 Web 服务正在获取数据,但不知何故没有显示在页面上。

我已经在网上搜索了很多,但无济于事。任何帮助表示赞赏

我得到的错误是:错误错误:找不到“对象”类型的不同支持对象“[对象对象]”。NgFor 仅支持绑定到 Iterables,例如 Arrays。

fetchdata.components.ts

import { Component, Inject } from '@angular/core';
import { FetchdataService } from '../fetchdata.service';
import { ServiceTypes } from '../models/servicetypes';

@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetchdata.component.html'
})
export class FetchDataComponent {

  serviceTypes: ServiceTypes[];
  serviceType: ServiceTypes;
  isLoaded = false;

 constructor(private _testService: FetchdataService) { }

 getServiceTypes(): void {
   this._testService.getServiceTypes().subscribe(data => {
     if(data) {
       this.serviceTypes = data;
       this.isLoaded = true;
       console.log('List of Service Types', this.serviceTypes);
     }
   } );
 }

 ngOnInit() {
   // fetch all the service types
   this.getServiceTypes();
   //this.serviceType = this.serviceTypes;
 }
}

fetchdata.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ServiceTypes } from './models/servicetypes';

@Injectable({
  providedIn: 'root'
})
export class FetchdataService {

  public testURL = 'https://api.myjson.com/bins/1dfxy8';

  constructor(private _http: HttpClient) { }

    getServiceTypes(): Observable<ServiceTypes[]> {
    return this._http.get<ServiceTypes[]>(this.testURL);
    }
  }

服务类型.ts

export interface ServiceTypes {
    Code:string;
    Description:string;
    VolumetricRatio: string
}

fetchdata.component.html

<p>fetchdata works!</p>


<p>This component demonstrates fetching data from the server.</p>



<select>
<option *ngFor="let serviceType of serviceTypes" [value]="serviceType.code">{{serviceTypes.Description}}</option>
</select>


<ul>
  <li *ngFor="let serviceType of serviceTypes">
      {{ serviceType.Code }}
  </li>
</ul>

控制台 日志显示数据和错误的控制台日志

标签: angular

解决方案


正如评论中所指出的,您在 API 响应中得到的是对象而不是数组。您需要将目标数组分配给您的变量。

代码:

this._testService.getServiceTypes().subscribe(data => {
     if(data) {
       this.serviceTypes = data.ServiceType; // <----- notice .ServiceType
       this.isLoaded = true;
       console.log('List of Service Types', this.serviceTypes);
     }
});

您还应该interface为响应创建一个新文件json并在您的服务方法中使用它。就像是:

export interface ServiceTypeApiModel {
    ServiceType: ServiceTypes[];
}

然后在您的service方法中,将响应转换为该模型,例如:

getServiceTypes(): Observable<ServiceTypeApiModel> {
  return this._http.get<ServiceTypeApiModel>(this.testURL);
}

推荐阅读