0

I'm writing a little ionic app for learning purposes and I would like to load data from a json file and assign it to an Interface that describes the data. But I'm struggling with getting it the right way:

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
            );
    };

}

I think only the line data => this.entries = data is wrong (also the IDE is telling me that), but I don't know to do this right and can't find documentation describing the correct way. If there actually is some I would be glad to know where I can find ressources about this.

1 Answer 1

1

subscribe return the response as an object, not as an array. So entries type should be changed.

entries: PhonebookEntry;

In the subscribe, need to assign a type for response data.

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

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.