Issue
I’m building a notes app, fetching data from a local api that I made.
Thing is, when I load data into my NoteModel in my component, values under the second "level" of models are undefined.
The data comes as a JSON
obviously, that I want to save into my Model:
[
{
"id": 1,
"note": [
{
"id": 1,
"title": "Test1",
"description": "Testing testing",
"completed": false
},
{
"id": 2,
"title": "Test2",
"description": "Testing testing",
"completed": false
},
{
"id": 3,
"title": "Test3",
"description": "Testing testing",
"completed": false
}
]
}
]
This is my NoteModel
import { NoteContent } from "./note-content-model"
export interface NoteModel {
Id: number;
NoteContent: NoteContent[];
}
And this is my NoteContent
model:
export interface NoteContent {
Id: number;
Title: string;
Description: string;
Completed: boolean;
}
As I understand it, it should load everything into both models when I save the JSON
into the model object, as I try in my home.component.ts
, that should load my list of components
import { Component, OnInit } from '@angular/core';
import { NoteService } from '../services/note.service';
import { NoteModel } from '../note-model';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
notes?: NoteModel;
constructor(private noteService: NoteService) { }
ngOnInit(): void {
this.noteService.getNotes()
.subscribe(response => {
if (response.length >= 0) {
this.notes = response[0];
console.log(this.notes.NoteContent)
}
});
}
}
Then I try to get the stored data in my html component using ngFor
but I dont get anything.
Solution
Your interfaces have properties that are named in PascalCase.
The received JSON has properties that are named in cammelCase.
Equally important is that your received JSON has a property name note
, but in your NoteModel
interface you named the property NoteContent
.
Replace your interfaces with the following and your code should work.
export interface NoteModel {
id: number;
note: NoteContent[];
}
export interface NoteContent {
id: number;
title: string;
description: string;
completed: boolean;
}
Answered By – Vasileios Kagklis
Answer Checked By – Candace Johnson (AngularFixing Volunteer)