Hello, I am currently attempting to retrieve data from a database and display it in a table. Below is the code for the service I have created:
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Subject } from "rxjs";
import { map } from 'rxjs/operators';
import { Post } from "./post.model";
@Injectable({ providedIn: "root" })
export class PostsService {
private posts: Post[] = [];
private postsUpdated = new Subject<Post[]>();
constructor(private http: HttpClient) {}
getPosts() {
this.http
.get<{ message: string; posts: any }>(
"http://localhost:3000/api/posts"
)
.pipe(map((postData) => {
return postData.posts.map(post => {
return {
title: post.title,
content: post.content,
id: post._id
};
});
}))
.subscribe(transformedPosts => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]);
});
}
getPostUpdateListener() {
return this.postsUpdated.asObservable();
}
addPost(title: string, content: string) {
const post: Post = { id: null, title: title, content: content };
this.http
.post<{ message: string, postId: string }>("http://localhost:3000/api/posts", post)
.subscribe(responseData => {
const id = responseData.postId;
post.id = id;
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
});
}
deletePost(postId: string) {
this.http.delete("http://localhost:3000/api/posts/" + postId)
.subscribe(() => {
const updatedPosts = this.posts.filter(post => post.id !== postId);
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
});
}
}
Upon running the code, two different errors are encountered:
When using Mozilla Firefox, the error received is:
ERROR TypeError: "_this.posts is undefined"
While using Google Chrome, the error displayed is:
core.js:1542 ERROR TypeError: Cannot read property 'slice' of undefined at SafeSubscriber._next (posts.service.ts:39)
If anyone has insights or suggestions on why these errors occur, please feel free to share. Thank you.