Skip to content

Commit

Permalink
post detail
Browse files Browse the repository at this point in the history
  • Loading branch information
jorbush committed Sep 28, 2024
1 parent 48250c5 commit 73f8bec
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ export class HomeComponent implements OnInit {
this.postService.getAllPosts().subscribe({
next: (posts) => {
this.posts = posts;
console.log(posts);
},
error: (err) => {
console.error(err);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,79 @@
import { Component } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { PostResponseDTO } from '../../models/post-response.model';
import { AuthService } from '../../services/auth.service';
import { PostService } from '../../services/post.service';
import { CommonModule } from '@angular/common';

@Component({
selector: 'app-post-detail',
standalone: true,
imports: [],
template: ` <p>post-detail works!</p> `,
imports: [CommonModule],
template: `
@if (post) {
<div>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<div>
<span>By: {{ post.user.username }}</span>
<span>{{ post.createdAt | date: 'short' }}</span>
</div>
@if (isLogged && post.user.username === username) {
<button (click)="editPost()">Edit</button>
<button (click)="deletePost()">Delete</button>
}
</div>
}
@if (!post) {
<p>Loading post...</p>
}
`,
styles: ``,
})
export class PostDetailComponent {}
export class PostDetailComponent implements OnInit {
post?: PostResponseDTO;
isLogged: boolean = false;
username?: string;

constructor(
private route: ActivatedRoute,
private postService: PostService,
private router: Router,
private authService: AuthService,
) {}

ngOnInit(): void {
const postId = Number(this.route.snapshot.paramMap.get('id'));
this.fetchPost(postId);
this.isLogged = this.authService.isAuthenticated();
this.username = localStorage.getItem('username') || '';
}

fetchPost(id: number): void {
this.postService.getPostById(id).subscribe({
next: (post) => (this.post = post),
error: (error) => console.error('Error fetching post', error),
});
}

editPost(): void {
if (this.post) {
this.router.navigate(['/edit', this.post.id]);
}
}

deletePost(): void {
if (this.post) {
if (confirm('Are you sure you want to delete this post?')) {
this.postService.deletePost(this.post.id).subscribe({
next: () => {
console.log('Post deleted successfully');
this.router.navigate(['/']);
},
error: (error) => console.error('Error deleting post', error),
});
}
}
}
}

0 comments on commit 73f8bec

Please sign in to comment.