I am building a Hacker News clone in Angular using the Hacker News API and I am attempting to display the comments that reply to a thread in a template.
I am finding it hard to understand what is being returned by the API (despite the .json in the api call!) and unable to grasp how to work with it.
In my service I have the following:
getCommentTree(commentId): Observable<any> {
return this.http
.get(`https://hacker-news.firebaseio.com/v0/item/${commentId}.json`);
}
The component is:
childCommentDetails: any[] = [];
constructor(private hackerNewsService: HackerNewsService) { }
ngOnInit() {
this.getChildCommentDetail(this.id);
}
getChildCommentDetail(id: number) {
this.hackerNewsService.getCommentTree(id).subscribe(
(data) => {
if (data !== null) {
this.childCommentDetails.push({ data });
}
},
(err) => console.log(`error ${err}`),
() => console.log('done')
);
}
The template is:
<div *ngFor="let comment of childCommentDetails">
<p [innerHTML]="comment.text"></p>
</div>
When this runs I do not see any output in my template.
However if I change the template to use the json pipe:
<div *ngFor="let comment of childCommentDetails">
<li>{{ comment | json}} </li>
</div>
The output in JSON is displayed. So I my assumption is that the API is returning JSON and I have then tried to convert it back to an object using JSON.parse. My getChildCommentDetail has changed to:
getChildCommentDetail(id: number) {
this.hackerNewsService.getCommentTree(id).subscribe(
(data) => {
if (data !== null) {
const obj = JSON.parse(data);
this.childCommentDetails.push({ obj });
}
},
(err) => console.log(`error ${err}`),
() => console.log('done')
);
}
However when I run this I see an error:
ERROR SyntaxError: Unexpected token o in JSON at position 1
What am I doing wrong?
childCommentDetails | json. But note that pushing into an array likely doesn't trigger a rerender.