I'm learning Angular basics. I've picked up a very small project. I'm using JSONPlaceholder, the fake REST API. I want to read all posts and render them on a the page using simple ngFor loop. I've created a service for that. I'll show my code one by one. But here's the stackblitz for the same.
I need help with these files only:
- post-list
- post interface
- post.service
I've written this much code from the scratch after reading atricles and watching tutorials on pluralsight and youtube but now I'm blocked. Here's 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 insist, please look at the stackblitz it will save everyone's time and efforts. My problems are:
Can't bind to 'ngForOf' since it isn't a known property of 'div'. ("
Error: 0.9.1/dist/zone.j
Please point out my mistakes and correct me.