【发布时间】:2020-02-17 04:34:00
【问题描述】:
我是 Angular 的新手,我试图从 Angular 8 中的 observable 填充下拉列表,但没有得到任何乐趣。 当我将数据写入控制台日志时,我可以看到 Web 服务正在获取数据,但不知何故没有显示在页面上。
我在网上搜索了很多次,但无济于事。任何帮助表示赞赏
我得到的错误是: ERROR 错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。
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);
}
}
serviceTypes.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>
【问题讨论】:
-
欢迎来到 Stackoverflow。听起来您正在尝试迭代对象而不是数组。你说你将数据打印到控制台日志?数据是什么样的?
-
那是因为你得到一个对象而不是一个数组作为响应。
-
嗨,卡斯滕,谢谢
标签: angular