【问题标题】:Reading content of json file in ionic app在离子应用程序中读取json文件的内容
【发布时间】:2018-06-01 01:24:24
【问题描述】:

我正在尝试使用 ionic 构建一个应用程序,该应用程序从本地“.json”文件中读取数据并使用这些数据来填充页面。但我已经在努力将文件导入页面。我目前拥有的是:

import { Component } from "@angular/core";

interface Entry {
    name:           string,
    telephone:      string
}

interface EntryList {
    entryList:  Array<Entry>;
}

@Component({
    selector:    'page-list',
    templateUrl: 'list.html'
})
export class ListPage {

    entryList: EntryList;

    constructor() {
        this.load_entries();
    };

    load_entries () {
        this.entryList = JSON.parse(
            // ?
        )
    };
}

.json 文件包含以下条目:

[
{"name": "Person A","telephone": "1234"},
{"name": "Person B","telephone": "12345"}
]

我不知道如何从这里开始。将我的数据导入应用的正确方法是什么?

【问题讨论】:

    标签: json angular cordova parsing ionic-framework


    【解决方案1】:

    请试试这个:

    constructor(public http: HttpClient) {
        this.load_entries();
    };
    
    load_entries(filePath: string) {  //filePath: 'assets/test.json'
    
        this.http
            .get(filePath)
            .subscribe((data) => {
               console.log(data);
            });
    }
    

    当然,你得先导入HttpClient

    import { HttpClient } from '@angular/common/http';
    

    【讨论】:

    • 不幸的是,这不起作用。我是否必须在其他地方添加HttpClient,例如app.module.ts
    • 感谢您的帮助,但现在当我打开它时,uncaught exception: [object Object] 已登录到控制台。不过,我无法使用try {} catch () {} 捕获此异常。我不知道还有什么问题。
    • 好吧,这是我的错。我以为我可以导入位于同一文件夹中的文件,但似乎我必须从 assets 目录加载它(正如您在评论中所写的那样)。现在它起作用了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多