我是nativescript的新手。我参考了官方杂货店应用列表视图 文档和我使用此Sample API来解析json格式 数据到listview。
看来我在命令提示符下没有收到任何错误。而且在 编码方面没有表现出任何问题。
我认为在解析结果并显示时出现问题 textField。我不知道我做错了什么。我的屏幕空白了 最后。
下面我发布了相关代码。请检查一下。
命令提示日志:
app.component.ts:
import { Component, OnInit } from "@angular/core";
import { MyHttpGetService } from "./app.component.services";
import "rxjs/add/operator/map";
import {Grocery} from "./grocery.model";
@Component({
moduleId: module.id,
templateUrl: "./app.component.html",
providers: [MyHttpGetService]
})
export class AppComponent implements OnInit {
groceryList: Array<Grocery> = [];
constructor(private myHttpGetService: MyHttpGetService) {}
ngOnInit() {
this.myHttpGetService.load()
.subscribe(loadedGroceries => {
loadedGroceries.forEach((groceryObject) => {
this.groceryList.unshift(groceryObject);
});
});
}
}
app.component.html:
<ListView [items]="groceryList" class="small-spacing">
<ng-template let-item="item">
<Label [text]="item.name" class="medium-spacing"></Label>
</ng-template>
</ListView>
app.services.ts:
import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import { Observable } from "rxjs/Rx";
import "rxjs/add/operator/map";
import { Grocery } from "./grocery.model";
@Injectable()
export class MyHttpGetService {
constructor(private http: Http) {}
static apiUrl = "http://api.androidhive.info/contacts/";
load() {
let headers = new Headers();
headers.append("Content-Type", "application/json");
return this.http.get(MyHttpGetService.apiUrl, {
headers: headers
})
.map(res => res.json())
.map(data => {
let groceryList = [];
data.Result.forEach((contacts) => {
groceryList.push(new Grocery(contacts.id, contacts.name));
});
return groceryList;
})
.catch(this.handleErrors);
}
handleErrors(error: Response) {
console.log(JSON.stringify(error.json()));
return Observable.throw(error);
}
}
grocery.model.ts:
export class Grocery {
constructor(public origin: string,public url: string) {
}
}
输出: