【问题标题】:Loading data from a json file with an Interface使用接口从 json 文件加载数据
【发布时间】:2018-06-04 07:27:34
【问题描述】:

我正在编写一个用于学习目的的小离子应用程序,我想从 json 文件加载数据并将其分配给描述数据的接口。但我正在努力以正确的方式获得它:

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

export interface PhonebookEntry {
    name:           string,
    telephone:      string, 
    description:    string
}

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

    entries: Array<PhonebookEntry>;

    constructor(public http: HttpClient) {
        this.load_entries('assets/json/phonebook.json');
    };

    load_entries(filePath: string) {
        return this.http.get(filePath)
            .subscribe(
                data => this.entries = data
            );
    };

}

我认为只有data =&gt; this.entries = data 行是错误的(IDE 也告诉我),但我不知道这样做是否正确,也找不到描述正确方法的文档。如果真的有一些,我会很高兴知道在哪里可以找到有关此的资源。

【问题讨论】:

    标签: json angular typescript ionic-framework


    【解决方案1】:

    subscribe 以对象而不是数组的形式返回响应。所以entries的类型应该改一下。

    entries: PhonebookEntry;
    

    在订阅中,需要为响应数据分配一个类型。

    load_entries(filePath: string) {
        return this.http.get(filePath)
            .subscribe(
                (data: PhonebookEntry) => this.entries = data // or use any type
            );
    };
    

    Demo

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多