【发布时间】:2019-04-03 22:45:06
【问题描述】:
我有一个 JSON 文件,其中包含待售物业列表。我正在尝试使用 *NgFor 循环遍历数据以创建列表。
首先,我仍然是 Angular 和应用程序开发的业余爱好者,所以我可能误解了文档等
我试过循环不同的路径
*NgFor="let post of posts.properties"
*NgFor="let post of posts.properties.property"
仍然出现各种错误。
我的理解是,我必须将 observable 转换为一组属性。然后将其绑定到html。 (我相信我所做的属性是数组类型?
json
{
"properties": {
"property": [
{
"propertyID": "101552000007",
"branchID": "1",
"clientName": "A Demo",
"branchName": "Brackley",
"department": "Sales",
"referenceNumber": "10006",
"addressName": "",
"addressNumber": "87",
"addressStreet": "Hackney Road",
properties.interface.ts
export interface IProperties {
addressStreet: string;
addressNumber: number;
}
For-sale.service.ts
import { IProperties } from './../properties.interface';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ForSaleService {
constructor(private http: HttpClient) {
}
getProperties(): Observable<IProperties[]> {
return this.http.get<IProperties[]>('/assets/data/jupix.json');
}
}
for-sale.page.ts
import { ForSaleService } from './for-sale.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-for-sale',
templateUrl: './for-sale.page.html',
styleUrls: ['./for-sale.page.scss'],
providers: [ForSaleService]
})
export class ForSalePage implements OnInit {
public properties = [];
constructor(private saleService: ForSaleService) { }
ngOnInit() {
this.onGetProperties();
}
onGetProperties() {
this.saleService.getProperties()
.subscribe(response => {
console.log(response);
this.properties = response;
});
}
}
html
<ion-content>
<ion-list *ngFor="let property of properties">
<ion-card>
<ion-card-header>{{ property.addressNumber }}</ion-card-header>
<ion-card-content>
<p>
<ion-icon name="person" color="primary"></ion-icon>
</p>
</ion-card-content>
</ion-card>
</ion-list>
</ion-content>
我不明白的是,让properties的property绑定到properties数组?
编辑:在尝试了一些建议之后,控制台日志中的错误似乎出现了一种模式?似乎看到子元素未定义,因为这些是引发错误的元素?
所以我将变量完全更改为 propertiesList 以使其更易于阅读。
现在发生了一件非常奇怪的事情。
所以我们有*ngFor="let property of propertiesList.properties.property"
然后是卡片图片<img src="{{ property.images.image[0].__text }}" alt="">
如图所示,这按预期工作。但是在控制台日志Cannot read property '__text' of undefined 和原来的" Cannot read property 'property' of undefined
所以我继续在 html 中添加其他元素
<ion-card-header>{{ property.addressNumber }} {{ property.addressStreet }} {{ property.addressPostcode }}</ion-card-header>
这些工作正常,没有错误,数据显示。现在这就是奇怪的地方。
<p>{{ property.propertyFeature1 }} {{ property.floorplans.floorplan._modified }}</p>
我现在添加这个,Cannot read property '__text' of undefined 消失了!而是替换为 Cannot read property '__modified' of undefined 以及原始的 Cannot read property 'property' of undefined
在 Visual Studio 代码中,我得到的唯一错误是 Identifier 'properties' is not defined. 'Array' does not contain such a member
【问题讨论】:
-
请在循环前检查
*ngIf="properties.properties.property?.length > 0"
标签: angular typescript api ionic-framework ngfor