第一次在堆叠溢出中问问题。我的ionic2应用程序有个问题。我可以在控制台上看到json,但是当我希望它在我的应用程序中显示时,news.html遇到了一些问题。
providers/news-data.ts
@Injectable()
export class NewsDataProvider {
data:any;
constructor(public http: Http) {
}
getUsers() {
if (this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('url').map(res => res.json()).subscribe(data => {
this.data = data;
resolve(this.data);
console.log('success');
});
});
}
}
news.ts
@IonicPage()
@Component({
selector: 'page-news',
templateUrl: 'news.html',
})
export class NewsPage {
users:any;
constructor(public navCtrl: NavController, public navParams: NavParams,public newsData:NewsDataProvider){
this.getUsers();
}
getUsers() {
this.newsData.getUsers().then(data => {
this.users = data;
});
}
}
news.html
<ion-header>
<ion-navbar color="danger" no-border-bottom>
<button ion-button menuToggle>
<ion-icon name="ios-contact"></ion-icon>
</button>
<ion-title></ion-title>
</ion-navbar>
<ion-toolbar no-border-top>
<ion-searchbar color="danger"
[(ngModel)]="queryText"
(ionInput)="updateSchedule()"
placeholder="Search">
</ion-searchbar>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-item *ngFor="let user of users">
{{user.title}}
</ion-item>
</ion-content>
控制台显示
错误:找不到“对象”类型不同的支持对象“对象对象”。NgFor只支持绑定到诸如数组之类的Iterable。NgForOf.ngOnChanges (core.es5.js:1689),checkAndUpdateDirectiveInline (core.es5.js:10790),checkAndUpdateNodeInline (core.es5.js:12216),checkAndUpdateNode (core.es5.js:12155),debugCheckAndUpdateNode (core.es5.js:12858),debugCheckDirectivesFn (core.es5.js:12799),Object.eval as updateDirectives at Object.debugUpdateDirectives as updateDirectives at checkAndUpdateView (core.es5.js:12122),callViewAction (core.es5.js:12485)
,但可以在网络中获取数据,那里有ald
发布于 2017-07-19 06:27:07
此错误意味着您正在ngFor
上使用ngFor
,但ngFor
只支持Array
等可迭代性。
我从您提供的url
中进行测试,发现您应该从res.json().data
检索,这是一个数组(应该是您希望在ngFor
上使用的数据)。请参阅以下更改。
this.http.get('http://bravonet.my/ct3/api/news?api_key=123').map(res => res.json().data).subscribe(data => {
this.data = data;
resolve(this.data);
console.log('success');
});
和柱塞演示(不要用Chrome来确认这一点,因为它会在默认情况下阻止http请求时使用https)。
发布于 2017-07-19 06:03:56
您已经订阅了函数中的http请求。不需要再做一次承诺,然后再回来。只需从news-data.ts
返回http请求并从news.ts
文件订阅它。
getUsers() {
if (this.data) {
return Promise.resolve(this.data);
}
return this.http.get('http://bravonet.my/ct3/api/news?api_key=123').map(res => res.json())
}
现在像这样抓住它
getUsers() {
this.newsData.getUsers().subscribe(data => {
this.users = data;
});
}
https://stackoverflow.com/questions/45182031
复制相似问题