Currently delving into the basics of Angular, I have embarked on a small project. Utilizing JSONPlaceholder, a fake REST API, my goal is to retrieve all posts and display them on a webpage through a straightforward ngFor
loop. For this purpose, I have devised a service. I will showcase my code step by step. However, here is the corresponding stackblitz.
I am seeking assistance with the following files:
- post-list
- post interface
- post.service
After diligently crafting this portion of the code based on articles and tutorial videos from platforms like Pluralsight and YouTube, I find myself at an impasse. Here is the excerpt of my code:
post.ts
export interface Post {
userId: number;
id: number;
title: string;
body: string;
}
post.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PostService {
constructor() {}
getAllPosts():Observable<Post[]> {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => console.log(json))
}
}
post-list.component.ts
import { PostService } from './post.service';
import { Component } from '@angular/core';
import { Post } from './post'
@Component({
templateUrl: './post-list.component.html',
})
export class PostList {
posts: Post[] = [];
errorMessage="";
constructor(private postservice: PostService) {
this.postservice.getAllPosts().subscribe({
next: posts => {
this.posts=posts;
},
error: err => this.errorMessage = err
});
}
}
I urge you to take a look at the stackblitz, as it can potentially save time and effort for everyone involved. My current obstacles are:
Can't bind to 'ngForOf' since it isn't a known property of 'div'. ("
Error: 0.9.1/dist/zone.j
Your guidance in pinpointing any mistakes and providing corrections would be greatly appreciated.