使用ng-repeat在ion-item中显示JSON文件的内容

时间:2017-12-23 12:46:46

标签: javascript json angular ionic-framework

我使用以下代码从JSON文件加载数据并将其显示在ion-list ion-item中,但它不起作用。我无法弄清楚我做这件事的方式有什么不妥。

import { Component } from "@angular/core"; 
import { HttpClient} from "@angular/common/http";

/**
 * Interface for a single Call entry
 * A Call always has a 'name:string' and a 'telephone:string', any 
 * other attribute is optional.
 */
export interface Call {
    name:           string,
    telephone:      string, 
    description?:   string,
    street?:        string,
    postal?:        string
}

/**
 * Interface for a list of Call entries 
 */
export interface CallList {
    calls: Call[];
}

/**
 * Class for a page that shows Call entries
 */
@Component({
    selector: 'page-calls',
    templateUrl: 'calls.html'
})
export class CallsPage {

    callList: CallList;

    /**
     * Constructor of CallsPage
     * @param http 
     */
    constructor(public http: HttpClient) {
        this.loadCalls('assets/json/calls.json');
        // console.log(this.callList); // does not work, just gives "undefined"
    };

    /**
     * Loads list of calls from a json file
     * @param filePath: Path to file that shall be loaded
     */
    loadCalls(filePath: string) {
        return this.http.get<CallList>(filePath).subscribe(
            data => { 
                this.callList = data; 
                // console.log(data); // works
            }
        );
    };
}

calls.json包含

[
{"name": "Police","telephone": "110","description": ""},
{"name": "Fire","telephone": "112","description": ""}
]

这是要使用的模板calls.html

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>

        <ion-title>Calls</ion-title>
    </ion-navbar>
</ion-header>

<ion-content>
    <ion-list>
        <ion-item ng-repeat="call in callList">
            {{call.name}}: {{call.telephone}}
        </ion-item>
    </ion-list>
</ion-content>

但是当我在我的应用程序中打开此页面时,控制台中会出现以下内容: Unhandled Promise rejection: _co.call is undefined ; Zone: <root> ; Task: Promise.then ; Value:。 我想我尝试从JSON导入数据的方式仍然存在问题。构造函数中的行已注释掉,只在控制台中显示undefined。然而,当我在.subscribe调用中执行相同操作时,它会打印出数据。所以我无法弄清楚问题出在哪里。

1 个答案:

答案 0 :(得分:3)

您需要使用 angular 语法 ngFor ,而不是 ng-repeat > angularjs 1.x 语法

<ion-item *ngFor="let call of callList">
    {{call.name}}: {{call.telephone}}
</ion-item>