angular - 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>
控制台 日志显示数据和错误的控制台日志
解决方案
正如评论中所指出的,您在 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);
}
推荐阅读
- sql-server - 没有类型定义的表值参数
- java - 摆脱“浮点上下文中的整数除法”警告
- java - 旧代码中的 TDD - 打破“构造函数”依赖项
- arrays - BigQuery:在 Array 中使用 Array 展平表
- c# - 使用 EF Core 动态使用 Linq 忽略重音字符
- python - JSON Handling: [Errno 36] File name too long
- lua - 使用 Lua 实现 Web 浏览器自动化
- php - PHP抓取外部网站的特定标签内容并返回href
- yocto - yocto OS需要使用git
- java - 如何从适配器类(不扩展 AppCompatActivity)调用 getSupportFragmentManager()?