Потратили много часов только на то, чтобы передать данные из API в ListView, не повезло.
_batches
получает JSON из API, я проверил его, используя console.log
, поэтому нет ошибок в JSON или на стороне сети. Тем не менее, данные не отображаются в ListView
.
Все выглядит как undefined
, проверяя это на эмуляторе.
Использование NS + Angular: все последние пакеты от 30 октября 2018
вот важная часть кода от компонента
import { Component, OnInit } from "@angular/core";
import { ObservableArray } from "data/observable-array";
import { Batch } from "../../shared/batch.model";
import { BatchesService } from "../../shared/batches.service";
import { finalize } from 'rxjs/operators';
@Component({
selector: "ns-batches",
moduleId: module.id,
templateUrl: "./batches.component.html",
})
export class BatchesComponent implements OnInit {
public _batches: ObservableArray < Batch > = new ObservableArray < Batch > ([]);
constructor(private _batchesService: BatchesService) {}
ngOnInit(): void {
this._batchesService.load()
.pipe(finalize(() => this._isLoading = false))
.subscribe((batches: Array < Batch > ) => {
this._batches = new ObservableArray(batches);
});
}
А это html-файл компонента
<StackLayout class="page">
<ListView [items]="_batches" class="list-group" id="listBatches">
<ng-template let-result="item">
<GridLayout columns="100, *" rows="auto, auto,auto,auto" horizontalAlignment="left" verticalAlignment="top" backgroundColor="#CCCCCC">
<img row="0" col="0" rowSpan="2" [src]="result.imageURL">
<Label row="0" col="1" [nsRouterLink]="['/item', result.id]" [text]="'ID : ' + result.id" class="h3"></Label>
<Label row="1" col="1" [text]="'Booked: ' + result.course" class="list-group-item"></Label>
<Label row="2" col="1" [text]="'Oral: ' + result.oralconfirm" class="list-group-item"></Label>
<Label row="3" col="0" colSpan="2" [text]="'Interested : ' + result.interested" class="list-group-item"></Label>
</GridLayout>
</ng-template>
</ListView>
</StackLayout>
А это из служебного файла
import { Injectable } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { map } from "rxjs/operators";
import { Observable } from 'rxjs';
import {Component, NgZone} from '@angular/core';
import { Batch } from "./batch.model";
@Injectable()
export class BatchesService {
private _batches = new Array < Batch > ();
constructor(private http: Http) {}
public load(): Observable < Batch[] > {
return this.http.get('https://appspages.something.com/something/test')
.pipe(map(res => res.json()));
}
}
решаемые
Добавление решения этой проблемы,
Наконец-то это сработало !!
Проблема была в JSON. Вот подробности -
Моя структура JSON была:
{
"records": [{
data of record 1
},
{
data of record 2
},
{
data of record 3
},
{
data of record n
}
]
}
Я должен удалить текст
{
"records":
от начала JSON и один }
в конце.
Этот модифицированный JSON работал хорошо.
Не уверен, есть ли решение для визуализации JSON, как я описал выше. Если вы знаете решение для этого, пожалуйста, напишите ниже.
Сидд, большое спасибо за помощь!
Вы великолепны!