angular - Nativescript Angular RadListView 无法从远程服务器获取数据
问题描述
我已经按照 git a RadListView 中的示例进行了实现,并且在从 .json 文件中获取数据时工作正常(就像在 git 示例中一样)
相反,当我进一步尝试从远程服务器获取数据时,RadListView 结果为空。
那么,我做错了什么?下面是我的源代码片段:
private initDataItems() {
// NOT WORKING: Fetching data from remote
// see the implementation of getAllRankings() below
this.rankingService.getAllRankings().subscribe(
(res) => {
this._sourceDataItems = new ObservableArray<DataItem>();
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < res.queryresult.length; i++) {
if (androidApplication) {
this._sourceDataItems.push(new DataItem(i, posts.names[i],
"This is item description",
posts.titles[i], posts.text[i], "res://" + posts.images[i].toLowerCase()));
console.log(this._sourceDataItems);
}
}
}
);
/*
// WORKING: Fetching data from .json file (post.json)
this._sourceDataItems = new ObservableArray<DataItem>();
for (let i = 0; i < posts.names.length; i++) {
if (androidApplication) {
this._sourceDataItems.push(new DataItem(i, posts.names[i],
"This is item description",
posts.titles[i], posts.text[i], "res://" + posts.images[i].toLowerCase()));
} else {
this._sourceDataItems.push(new DataItem(i,
posts.names[i], "This is item description",
posts.titles[i], posts.text[i], "res://" + posts.images[i]));
}
}
*/
}
}
其中 getAllRankings() 看起来像:
getAllRankings() {
return this.http.get<{ queryresult: any }>("http://api.dev.blabla.com/posts");
}
解决方案
在开始时创建您的数组对象,以便您的模板可以呈现一些东西。然后,因为您的网络调用的回调将在角度区域之外,所以将其放回内部。
import { ..., NgZone } from '@angular/core';
constructor( ..., private zone: NgZone) {
...
}
private initDataItems() {
this._sourceDataItems = new ObservableArray<DataItem>();
// see the implementation of getAllRankings() below
this.rankingService.getAllRankings().subscribe(
(res) => {
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < res.queryresult.length; i++) {
if (androidApplication) {
this.zone.run(() => {
this._sourceDataItems.push(new DataItem(i, posts.names[i],
"This is item description",
posts.titles[i], posts.text[i], "res://" + posts.images[i].toLowerCase()));
console.log(this._sourceDataItems);
});
}
}
}
);
}
或者,您也可以使用变化检测器做一些事情。
注意:为避免一次推送一个并触发要检测到的一系列顺序更改,最好使用传播推送。
this._sourceDataItems.push(...res.queryresult.map((res) => new DataItem( ... )));
推荐阅读
- virtualbox - 我无法理解符号文件正常运行
- react-native - 反应原生元素位置?
- blockchain - 如何部署多个使用彼此功能的solidity智能合约?
- c# - How can I iterate over a ProcessThreadCollection to access a property of each object inside the collection?
- java - Java 8 流延迟在实践中没有用吗?
- ios12 - 如何使用 Siri 快捷方式打开应用程序?
- java - 用于打印到文件的循环永远加载并且即使关闭也文件空白?
- vba - 当单元格为空白并且有很多例程时如何处理错误
- python - python read data from variable and write to a file (no print) which i wanted to use later as backup data
- python - Seamlessly and efficiently flipping numpy array or sparse matrix along all axes