I made a very normal HTTP request to get one object from a JSON file. but I noticed I get all the file's data instead of the only needed object. following my code demonstrates how I made a class to fetch needed data but it still not working as planned for some reason.
JSON file (DB.json) => I need just (articles)
{
"articles": [
{
"id": "1",
"title": "Title 1",
"body": "what ever ... ",
"date": "14/03/2020",
"rating": 4,
"pic": "../../assets/images/cat.jpg"
},
{
"id": "2",
"title": "Title 2",
"body": "what ever ... ",
"date": "15/03/2020",
"rating": 5,
"pic": "../../assets/images/dog.jpg"
}
],
AnotherTableName [ ... etc ],
AnotherTableName [ ... etc ]
}
article.ts => the class
export class Article {
id: string;
title: string;
body: string;
date: Date;
rating: number;
pic: string;
}
component.ts
export class ArticleComponent implements OnInit {
constructor(private httpGetArticles: ArticleService) { }
errMess: string;
articles: Article[];
ngOnInit(){
this.httpGetArticles.getArticles().subscribe(
data => this.articles = data,
errmess => this.errMess = <any>errmess,
() => console.log(this.articles));
}
}
component.html
<p *ngFor="let artcl of articles">
<span>artcl.title</span>>
</p>
Service
getArticles(): Observable<Article[]> {
return this.http.get<Article[]>("./assets/DB.json")
.pipe(catchError(this.handleHttpErrService.handleError));
}
console.log( .. result
Object {
articles: Array [ {…}, {…} ]
feedback: Array(13) [ {…}, {…}, {…}, … ]
leaders: Array(4) [ {…}, {…}, {…}, … ]
promotions: (1) […]
Despite I get the object as shown, I got also the following error ( I think because I use NgFor for one object named articles but retrieved data come up with a different format "the whole JSON file" )
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
So I need to retrieve the casted data only (articles) not all the JSON file