我的API看起来像这样: my API
问题在于,当我想使用API进行数据绑定时,我得到的错误是数据绑定仅对于数组可能。不是对象。我需要的API是只有城市。我想出的可能是因为json文件是一个嵌套对象,不能转换成数组。所以我想看看是否有办法提取城市并将其放入数组用于绑定。要明确我发布我的代码: 获取API的 StatesProvider :
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class StatesProvider {
constructor(public http: HttpClient, public platform: Platform) {}
getCities() {
return new Promise(resolve => {
this.http.get("https://***"+lang+"/state/1").subscribe(data => {
resolve(data);
}, err => {
console.log(err);
});
});
}}
我的 state.ts组件:
import { Component, ViewChild } from '@angular/core';
import { NavController, App, ViewController, Slides } from 'ionic-angular';
import { StatesProvider } from '../../providers/states/states';
@Component({
selector: 'page-state',
templateUrl: 'sell.html'
})
export class StatePage {
@ViewChild('mySlider') slider: Slides;
cities: any;
constructor(public viewCtrl: ViewController, public appCtrl: App,
public navCtrl: NavController, public stateProvide: StatesProvider) {
this.getCities();
}
getCities() {
this.stateProvide.getCities()
.then(data => {
this.cities = data;
console.log(this.cities);
});
}
最后是 html 文件,我遇到问题的部分看起来像那样:
<ion-content padding>
<ion-slides #mySlider (ionDidChange)="onSlideChanged($event)">
<ion-slide *ngFor="let city of cities.cities">
<ion-list>
<ion-item>
<ion-thumbnail item-left>
<img [src]="city.image_thumb">
</ion-thumbnail>
<h2 text-end>{{city.name}}</h2>
</ion-item>
</ion-list>
</ion-slide>
</ion-slides>
</ion-content>
现在,当我读到某个地方时,对于像这样的API,你可以使用* ngFor,就像我写的那样: * ngFor =&#34;让city.cities&#34; 即可。但我仍然得到错误:无法读取属性&#39; cities&#39;未定义的
答案 0 :(得分:1)
您的代码似乎很好,请尝试使用安全导航?
-
<ion-slide *ngFor="let city of cities?.cities">