Added blog functionality, reworked backend api requests

This commit is contained in:
itzMiney committed 2024-12-29 23:32:35 +01:00
1 parent a4b69c5b9a
commit dae95810f2
16 files changed
+669 -144

No files matched your search

+83 -24
View File
@@ -4,27 +4,67 @@
position: fixed; position: fixed;
top: 0; top: 0;
left: 0; left: 0;
width: 100vw; /* Full viewport width */ width: 100vw;
height: 100vh; /* Full viewport height */ height: 100vh;
z-index: -100; /* Place the background behind content */ z-index: -100;
}
.admin-container {
background: #fff;
border-radius: 25px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 40px;
width: 350px;
text-align: center;
margin: 50px auto;
} }
.height-container { .height-container {
min-height: 100vh; display: flex;
align-content: center; justify-content: space-between;
align-items: center;
height: 100vh;
width: 100vw;
} }
.admin-actions button { .center-section,
.left-section,
.right-section {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 33.33%;
padding: 30px;
height: auto;
box-sizing: border-box;
}
.admin-dashboard-tile,
.create-article-tile,
.articles-list-tile {
background: #fff;
border-radius: 25px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 20px;
text-align: center;
max-width: 400px;
width: 100%;
}
.admin-dashboard-tile,
.create-article-tile {
margin-bottom: 30px;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.articles-list-tile {
overflow-y: auto;
max-width: 300px;
}
input,
textarea {
width: 90%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 25px;
}
.admin-actions button, .create-article-tile button {
background-color: #bd3948; background-color: #bd3948;
color: white; color: white;
padding: 12px 20px; padding: 12px 20px;
@@ -34,11 +74,11 @@
cursor: pointer; cursor: pointer;
} }
.admin-actions button:hover { .admin-actions button:hover, .create-article-tile button:hover {
background-color: #e3485a; background-color: #e3485a;
} }
.logout button { .admin-actions button.logout {
background-color: #713252; background-color: #713252;
color: white; color: white;
padding: 12px 20px; padding: 12px 20px;
@@ -48,18 +88,37 @@
cursor: pointer; cursor: pointer;
} }
.logout button:hover { .admin-actions button.logout:hover {
background-color: #592840; background-color: #592840;
} }
.articles-list { .articles-list-tile ul {
margin-top: 20px; list-style-type: none;
text-align: left; padding: 0;
overflow-y: auto;
max-height: 100%;
} }
.article { .articles-list-tile li {
border: 1px solid #ccc; border: 1px solid #ccc;
padding: 10px; padding: 10px;
margin-bottom: 10px; margin-bottom: 10px;
border-radius: 4px; border-radius: 25px;
}
.articles-list-tile li:last-child {
margin-bottom: 0;
}
.articles-list-tile h2 {
margin-bottom: 30px;
}
.articles-list-tile {
padding-bottom: 5px;
}
textarea {
resize: none;
min-height: 100px;
} }
+36 -13
View File
@@ -1,29 +1,52 @@
<div id="admin-bg"></div> <div id="admin-bg">
<div class="height-container"> <div class="height-container">
<div class="admin-container"> <!-- Left Section: Placeholder -->
<div class="left-section">
<!-- Placeholder for future content -->
</div>
<!-- Center Section: Admin Dashboard and Create Article Tiles -->
<div class="center-section">
<div class="admin-dashboard-tile">
<h2>Admin Dashboard</h2> <h2>Admin Dashboard</h2>
<div class="admin-actions"> <div class="admin-actions">
<button (click)="createArticle()">Create Article</button>
<button (click)="viewArticles()">View Articles</button>
<button (click)="editArticle()">Edit Article</button> <button (click)="editArticle()">Edit Article</button>
<button (click)="deleteArticle()">Delete Article</button> <button (click)="deleteArticle()">Delete Article</button>
<button class="logout" (click)="logout()">Logout</button>
</div>
</div> </div>
<div class="create-article-tile">
<h2>Create New Article</h2>
<form (ngSubmit)="createArticle()">
<div>
<label for="title">Title:</label>
<input type="text" id="title" [(ngModel)]="title" name="title" required />
</div>
<div>
<label for="content">Content:</label>
<textarea id="content" [(ngModel)]="content" name="content" required></textarea>
</div>
<button type="submit" [disabled]="!title || !content">Create Article</button>
</form>
</div>
</div>
<!-- Right Section: Articles List Tile -->
<div class="right-section">
<div class="articles-list-tile">
<h2>Articles</h2>
<div *ngIf="noArticles"> <div *ngIf="noArticles">
<p>No articles available.</p> <!-- Show message if no articles --> <p>No articles available.</p>
</div> </div>
<div *ngIf="!noArticles"> <div *ngIf="!noArticles">
<ul> <ul>
<li *ngFor="let article of articles"> <li *ngFor="let article of articles">
<!-- Display article details here --> <strong>ID {{ article.id }}</strong> - {{ article.title }}
{{ article.title }}
</li> </li>
</ul> </ul>
</div> </div>
</div>
<div class="logout"> </div>
<button (click)="logout()">Logout</button>
</div> </div>
</div> </div>
</div>
+116 -38
View File
@@ -3,6 +3,7 @@ import {Router} from '@angular/router';
import {ArticleService} from '../services/article.service'; import {ArticleService} from '../services/article.service';
import {NgFor, NgIf} from '@angular/common'; import {NgFor, NgIf} from '@angular/common';
import {Observer} from 'rxjs'; import {Observer} from 'rxjs';
import {FormsModule} from '@angular/forms';
@Component({ @Component({
selector: 'app-admin', selector: 'app-admin',
@@ -10,23 +11,33 @@ import {Observer} from 'rxjs';
styleUrls: ['./admin.component.css'], styleUrls: ['./admin.component.css'],
imports: [ imports: [
NgIf, NgIf,
NgFor NgFor,
FormsModule,
] ]
}) })
export class AdminComponent implements OnInit { export class AdminComponent implements OnInit {
articles: any[] = []; articles: any[] = [];
noArticles: boolean = false; noArticles: boolean = false;
constructor(private articleService: ArticleService, private router: Router) {} title: string = '';
content: string = '';
token: string | null = localStorage.getItem('token');
ngOnInit() { constructor(
this.fetchArticles(); private articleService: ArticleService,
} private router: Router
) {}
// Fetch articles from backend // Fetch articles from backend
fetchArticles() { ngOnInit() {
const token = localStorage.getItem('token'); if (!this.token) {
if (!token) { this.navigateToLogin();
return;
}
this.loadArticles()
}
navigateToLogin() {
this.router.navigate(['/login']).then( this.router.navigate(['/login']).then(
(success) => { (success) => {
if (success) { if (success) {
@@ -39,9 +50,104 @@ export class AdminComponent implements OnInit {
console.error('Navigation error:', error); console.error('Navigation error:', error);
} }
); );
}
createArticle() {
if (!this.token) {
this.navigateToLogin();
return; return;
} }
if (!this.title || !this.content) {
alert('Both title and content are required!');
return;
}
this.articleService.postArticle(this.token, this.title, this.content).subscribe(
(response) => {
alert('Article created successfully!');
this.loadArticles();
console.log(response); // You can log the response or take further actions like redirecting
},
(error) => {
alert('Error creating article');
console.error(error); // Log the error for debugging
}
);
}
editArticle(): void {
if (!this.token) {
this.navigateToLogin();
return;
}
const articleId = prompt('Enter the article ID to edit:');
if (articleId && !isNaN(Number(articleId))) {
const id = Number(articleId);
// Fetch the current article to get existing values
this.articleService.getArticleById(id).subscribe(
(article) => {
if (!article) {
alert(`Article with ID ${id} not found.`);
return;
}
// Prompt for title and content with placeholders
const newTitle = prompt('Enter the new title (Leave blank to leave as is):');
const newContent = prompt('Enter the new content (Leave blank to leave as is):');
// Use current values if left blank
const updatedTitle = newTitle?.trim() || article.title;
const updatedContent = newContent?.trim() || article.content;
this.articleService.editArticle(id, this.token, updatedTitle, updatedContent).subscribe(
(response) => {
alert(`Article ${id} updated successfully!`);
console.log('Updated Article:', response);
this.loadArticles();
},
(error) => {
alert(`Error updating article ${id}: ${error.message}`);
}
);
},
(error: { message: any; }) => {
alert(`Failed to fetch article with ID ${id}: ${error.message}`);
}
);
} else {
alert('Invalid input. Please enter a valid article ID.');
}
}
deleteArticle(): void {
if (!this.token) {
this.navigateToLogin();
return;
}
const articleId = prompt('Enter the article ID to delete:');
if (articleId && !isNaN(Number(articleId))) {
const id = Number(articleId);
this.articleService.deleteArticle(id, this.token).subscribe(
() => {
alert(`Article ${id} deleted successfully`);
this.loadArticles();
},
(error) => {
alert(`Error deleting article ${id}: ${error.message}`);
}
);
} else {
alert('Invalid input. Please enter a valid article ID.');
}
}
loadArticles(): void {
const articleObserver: Observer<any> = { const articleObserver: Observer<any> = {
next: (data) => { next: (data) => {
this.articles = data; this.articles = data;
@@ -54,39 +160,11 @@ export class AdminComponent implements OnInit {
console.log('Article loading complete'); console.log('Article loading complete');
} }
}; };
this.articleService.getAllArticles().subscribe(articleObserver);
this.articleService.getArticles(token).subscribe(articleObserver);
}
createArticle() {
alert('Create article functionality goes here');
}
editArticle() {
alert('Delete article functionality goes here');
}
deleteArticle() {
alert('Delete article functionality goes here');
}
viewArticles() {
this.fetchArticles();
} }
logout() { logout() {
localStorage.removeItem('token'); localStorage.removeItem('token');
this.router.navigate(['/login']).then( this.navigateToLogin();
(success) => {
if (success) {
console.log('Navigation to login succeeded');
} else {
console.warn('Navigation to login failed');
}
},
(error) => {
console.error('Navigation error:', error);
}
);
} }
} }
+3 -24
View File
@@ -4,9 +4,9 @@ import {ActivatedRoute, NavigationEnd, Router, RouterOutlet} from '@angular/rout
import {NavbarComponent} from './navbar/navbar.component'; import {NavbarComponent} from './navbar/navbar.component';
import {MobileNavbarComponent} from './mobile-navbar/mobile-navbar.component'; import {MobileNavbarComponent} from './mobile-navbar/mobile-navbar.component';
import {FooterComponent} from './footer/footer.component'; import {FooterComponent} from './footer/footer.component';
import {Meta, Title} from '@angular/platform-browser';
import {filter, map, mergeMap} from 'rxjs/operators'; import {filter, map, mergeMap} from 'rxjs/operators';
import {DeviceDetectorService} from './services/device-detector.service'; import {DeviceDetectorService} from './services/device-detector.service';
import { UpdateMetaService } from './services/update-meta.service';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@@ -22,9 +22,8 @@ export class AppComponent implements OnInit {
constructor( constructor(
private router: Router, private router: Router,
private activatedRoute: ActivatedRoute, private activatedRoute: ActivatedRoute,
private titleService: Title,
private metaService: Meta,
private deviceService: DeviceDetectorService, private deviceService: DeviceDetectorService,
private updateMetaService: UpdateMetaService,
) {} ) {}
ngOnInit() { ngOnInit() {
@@ -50,31 +49,11 @@ export class AppComponent implements OnInit {
meta.url = meta.url || 'https://itzminey.dev'; meta.url = meta.url || 'https://itzminey.dev';
meta.color = meta.color || '#eb284c'; meta.color = meta.color || '#eb284c';
} }
this.updateMetaTags(meta); this.updateMetaService.updateMetaTags(meta);
this.checkRoute(); this.checkRoute();
}); });
} }
updateMetaTags(meta: { title?: string; description?: string; image?: string; url?: string; color?: string }) {
if (meta.title) {
this.titleService.setTitle(meta.title);
this.metaService.updateTag({ name: 'og:title', content: meta.title });
}
if (meta.description) {
this.metaService.updateTag({ name: 'description', content: meta.description });
this.metaService.updateTag({ name: 'og:description', content: meta.description });
}
if (meta.image) {
this.metaService.updateTag({ name: 'og:image', content: meta.image });
}
if (meta.url) {
this.metaService.updateTag({ name: 'og:url', content: meta.url });
}
if (meta.color) {
this.metaService.updateTag({ name: 'theme-color', content: meta.color});
}
}
checkRoute() { checkRoute() {
const currentRoute = this.activatedRoute.snapshot.firstChild?.routeConfig?.path; const currentRoute = this.activatedRoute.snapshot.firstChild?.routeConfig?.path;
+4
View File
@@ -17,6 +17,10 @@ export const serverRoutes: ServerRoute[] = [
path: 'blog', path: 'blog',
renderMode: RenderMode.Prerender, renderMode: RenderMode.Prerender,
}, },
{
path: 'blog/:slug',
renderMode: RenderMode.Client,
},
{ {
path: 'admin', path: 'admin',
renderMode: RenderMode.Client, renderMode: RenderMode.Client,
+4
View File
@@ -5,6 +5,7 @@ import {BlogComponent} from './blog/blog.component';
import {NotFoundComponent} from './not-found/not-found.component'; import {NotFoundComponent} from './not-found/not-found.component';
import {LoginComponent} from './login/login.component'; import {LoginComponent} from './login/login.component';
import {AdminComponent} from './admin/admin.component'; import {AdminComponent} from './admin/admin.component';
import {ArticlePageComponent} from './article-page/article-page.component';
export const routes: Routes = [ export const routes: Routes = [
{ {
@@ -77,6 +78,9 @@ export const routes: Routes = [
} }
} }
}, },
{
path: 'blog/:slug',
component: ArticlePageComponent },
{ {
path: '**', path: '**',
pathMatch: 'full', pathMatch: 'full',
@@ -0,0 +1,114 @@
@keyframes fadeIn {
0% {
opacity: 0;
visibility: hidden;
}
100% {
opacity: 1;
visibility: visible;
}
}
#vanta-article-bg {
animation: fadeIn 1s ease-out;
position: fixed;
top: 0;
left: 0;
width: 100vw; /* Full viewport width */
height: 100vh; /* Full viewport height */
z-index: -100; /* Place the background behind content */
}
.height-container {
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
text-align: center;
z-index: 10;
}
.article-container {
z-index: 1;
width: 100%;
min-height: 100vh;
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 50%, rgb(0, 0, 0) 100%);
padding: 30px;
justify-items: center;
align-items: center;
}
.content-container {
display: inline-grid;
max-width: 960px;
}
h1 {
font-size: 2.5rem;
color: #fff;
margin-top: 120px;
margin-bottom: 40px;
font-weight: 600;
}
.article-content {
font-size: 1.2rem;
color: #fff;
line-height: 1.8; /* Improve readability */
margin-bottom: 30px;
}
.article-meta {
font-size: 1rem;
color: #e6e6e6;
text-align: left;
}
.article-meta p {
margin: 8px 0;
}
.content-container button {
background-color: #713252;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
border-radius: 25px;
transition: background-color 0.3s;
font-weight: 400;
}
.content-container button:hover {
background-color: #bf9bae;
}
.error-message h1 {
font-size: 10rem;
margin: 0;
font-weight: 700;
color: white;
}
.error-message p {
font-size: 1.5rem;
margin: 20px 0;
font-weight: 400;
color: white;
}
.error-message button {
background-color: #713252;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
border-radius: 25px;
transition: background-color 0.3s;
font-weight: 400;
}
.error-message button:hover {
background-color: #bf9bae;
}
@@ -0,0 +1,30 @@
<div id="vanta-article-bg"></div>
<div class="height-container">
<div class="article-container" *ngIf="article; else error">
<div>
<!-- Article Title -->
<h1>{{ article.title }}</h1>
<div class="content-container">
<!-- Article Content -->
<div class="article-content" [innerHTML]="article.content"></div>
<a href="/blog"><button>Back to Overview</button></a>
<!-- Article Metadata -->
<div class="article-meta">
<p><strong>Author:</strong> {{ article.authorName}}</p>
<p><strong>Views:</strong> {{ article.views }}</p><br>
<p><strong>Created At:</strong> {{ article.createdAt | date:'medium' }}</p>
<p><strong>Last Updated:</strong> {{ article.updatedAt | date:'medium' }}</p>
</div>
</div>
</div>
</div>
<!-- Error Message -->
<ng-template #error>
<div class="error-message">
<h1>404</h1>
<p>Article not found!</p>
<a href="/blog"><button>Back to Overview</button></a>
</div>
</ng-template>
</div>
@@ -0,0 +1,130 @@
import {AfterViewInit, Component, Inject, OnDestroy, OnInit, PLATFORM_ID} from '@angular/core';
import {DeviceDetectorService} from '../services/device-detector.service'
import {DatePipe, isPlatformBrowser, NgIf} from '@angular/common';
import {VantaBackgroundService} from '../services/vanta-background.service';
import {ArticleService} from '../services/article.service';
import {ActivatedRoute} from '@angular/router';
import {UpdateMetaService} from '../services/update-meta.service';
interface Article {
id: number;
title: string;
slug: string;
content: string;
createdAt: string;
updatedAt: string;
views: number;
authorId: number;
authorName: string;
}
@Component({
selector: 'app-article-page',
imports: [
NgIf,
DatePipe
],
templateUrl: './article-page.component.html',
styleUrl: './article-page.component.css'
})
export class ArticlePageComponent implements OnInit, OnDestroy, AfterViewInit {
private readonly elementId = 'vanta-article-bg';
isMobile: boolean = false;
article: Article | undefined;
currentArticle: any;
constructor(
private deviceService: DeviceDetectorService,
private vantaService: VantaBackgroundService,
private articleService: ArticleService,
private updateMetaService: UpdateMetaService,
private route: ActivatedRoute,
@Inject(PLATFORM_ID) private platformId: Object
) {
}
ngOnInit() {
this.isMobile = this.deviceService.isMobile;
this.route.params.subscribe((params) => {
const slug = params['slug'];
if (slug) {
this.loadArticleMetaBySlug(slug);
} else {
this.updateMetaService.updateMetaTags({
title: 'Article | itzMiney',
description: 'An article on itzMiney\'s Blog.',
image: 'https://itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/blog',
color: '#ffffff'
});
}
});
if (isPlatformBrowser(this.platformId)) {
window.addEventListener('resize', this.onResize.bind(this));
}
const slug = this.route.snapshot.paramMap.get('slug') || '';
this.articleService.getArticleBySlug(slug).subscribe(
(article) => {
this.article = article;
console.log('Article found!')
},
(error) => {
console.error('Error fetching article:', error);
}
);
}
ngAfterViewInit() {
this.vantaService.initVanta(this.elementId, {
color: 0xac1f4e,
backgroundColor: 0x191522
});
}
ngOnDestroy() {
this.vantaService.destroyVanta(this.elementId);
if (isPlatformBrowser(this.platformId)) {
window.removeEventListener('resize', this.onResize);
}
}
onResize() {
this.vantaService.resizeVanta(this.elementId);
}
loadArticleMetaBySlug(slug: string) {
this.articleService.getArticleBySlug(slug).subscribe(
(article) => {
if (article) {
this.currentArticle = article;
this.updateMetaService.updateMetaTags({
title: article.title,
description: article.content.slice(0, 150), // First 150 characters
image: 'https://itzminey.dev/assets/ogimg.png', // Use article image or default
url: `https://itzminey.dev/blog/${article.slug}`,
color: '#ffffff'
});
} else {
console.warn('Article not found for slug:', slug);
this.updateMetaService.updateMetaTags({
title: 'Article Not Found',
description: 'The requested article could not be found.',
image: 'https://itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev',
color: '#ff0000'
});
}
},
(error) => {
console.error('Failed to load article metadata', error);
this.updateMetaService.updateMetaTags({
title: 'Error',
description: 'An error occurred while loading this article.',
image: 'https://itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev',
color: '#ff0000'
});
}
);
}
}
+25 -20
View File
@@ -28,30 +28,35 @@
z-index: 10; /* Ensure the text and button are above the canvas */ z-index: 10; /* Ensure the text and button are above the canvas */
} }
.error-message h2 { .blog-container {
font-size: 10rem; max-width: 900px;
margin: 0; margin-top: 120px;
font-weight: 700; margin-bottom: 80px;
color: white; padding: 20px;
} }
.error-message p { .article-card {
font-size: 1.5rem; z-index: 10;
margin: 20px 0; background: linear-gradient(135deg, #9c27b0, #6200ea);
font-weight: 400; padding: 15px;
color: white; margin: 25px 0;
cursor: pointer;
border-radius: 45px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: background-color 0.3s, transform 0.2s;
} }
.error-message-mobile h2 { .article-card:hover {
font-size: 4.0rem; background: linear-gradient(135deg, #b737cd, #773ec6);
margin: 0; transform: translateY(-5px);
font-weight: 500;
color: white;
} }
.error-message-mobile p { h2 {
font-size: 1.2rem; font-size: 1.6rem;
margin: 10px 0; color: #ffffff;
font-weight: 400; }
color: white;
p {
font-size: 1rem;
color: #dcdcdc;
} }
+10 -10
View File
@@ -1,15 +1,15 @@
<div id="vanta-blog-bg"></div> <div id="vanta-blog-bg"></div>
<div class="height-container"> <div class="height-container">
<ng-container *ngIf="!isMobile; else mobileError"> <div class="blog-container">
<div class="error-message"> <div *ngIf="articles$ | async as articles; else noArticles">
<h2>Soon&#8482;</h2> <div *ngFor="let article of articles" (click)="navigateToArticle(article.slug)" class="article-card">
<p>Under Construction!</p> <h2>{{ (article.title | slice:0:45) + (article.title.length > 40 ? '...' : '')}}</h2>
<p>{{ (article.content | slice:0:80) + (article.content.length > 80 ? '...' : '')}}</p>
<p><small>By {{ article.authorName }} | {{ article.createdAt | date: 'short' }}</small></p>
</div> </div>
</ng-container>
<ng-template #mobileError>
<div class="error-message-mobile">
<h2>Soon&#8482;</h2>
<p>Under Construction!</p>
</div> </div>
</ng-template> </div>
<ng-template #noArticles>
<h2>No Articles yet!</h2>
</ng-template>
</div> </div>
+18 -4
View File
@@ -1,31 +1,45 @@
import {AfterViewInit, Component, Inject, OnDestroy, OnInit, PLATFORM_ID} from '@angular/core'; import {AfterViewInit, Component, Inject, OnDestroy, OnInit, PLATFORM_ID} from '@angular/core';
import {DeviceDetectorService} from '../services/device-detector.service' import {DeviceDetectorService} from '../services/device-detector.service'
import {isPlatformBrowser, NgIf} from '@angular/common'; import {DatePipe, isPlatformBrowser, NgIf, NgFor, AsyncPipe, SlicePipe} from '@angular/common';
import {VantaBackgroundService} from '../services/vanta-background.service'; import {VantaBackgroundService} from '../services/vanta-background.service';
import { ArticleService } from '../services/article.service';
import { Router } from '@angular/router';
import {Observable} from 'rxjs';
@Component({ @Component({
selector: 'app-blog', selector: 'app-blog',
imports: [ imports: [
NgIf NgIf,
NgFor,
DatePipe,
AsyncPipe,
SlicePipe
], ],
templateUrl: './blog.component.html', templateUrl: './blog.component.html',
styleUrl: './blog.component.css' styleUrl: './blog.component.css'
}) })
export class BlogComponent implements OnInit, OnDestroy, AfterViewInit { export class BlogComponent implements OnInit, OnDestroy, AfterViewInit {
articles$: Observable<any[]> | undefined;
private readonly elementId = 'vanta-blog-bg'; private readonly elementId = 'vanta-blog-bg';
isMobile: boolean = false; isMobile: boolean = false;
constructor( constructor(
private deviceService: DeviceDetectorService, private deviceService: DeviceDetectorService,
private vantaService: VantaBackgroundService, private vantaService: VantaBackgroundService,
private articleService: ArticleService,
private router: Router,
@Inject(PLATFORM_ID) private platformId: Object @Inject(PLATFORM_ID) private platformId: Object
) { ) {}
}
ngOnInit() { ngOnInit() {
this.isMobile = this.deviceService.isMobile; this.isMobile = this.deviceService.isMobile;
if (isPlatformBrowser(this.platformId)) { if (isPlatformBrowser(this.platformId)) {
window.addEventListener('resize', this.onResize.bind(this)); window.addEventListener('resize', this.onResize.bind(this));
} }
this.articles$ = this.articleService.getAllArticles();
}
navigateToArticle(slug: string): void {
this.router.navigate([`/blog/${slug}`]);
} }
ngAfterViewInit() { ngAfterViewInit() {
+11 -6
View File
@@ -1,7 +1,7 @@
import {Component, OnInit} from '@angular/core'; import {Component, OnInit} from '@angular/core';
import {NavigationEnd, Router, RouterLink} from '@angular/router'; import {NavigationEnd, Router, RouterLink} from '@angular/router';
import {DeviceDetectorService} from 'ngx-device-detector'; import {DeviceDetectorService} from 'ngx-device-detector';
import {NgIf} from '@angular/common'; import {filter} from 'rxjs/operators';
@Component({ @Component({
selector: 'app-navbar', selector: 'app-navbar',
@@ -19,11 +19,16 @@ export class NavbarComponent implements OnInit {
this.isMobile = this.deviceService.isMobile(); this.isMobile = this.deviceService.isMobile();
} }
ngOnInit() { ngOnInit(): void {
// Listen to route changes this.router.events.pipe(
this.router.events.subscribe((event) => { filter(event => event instanceof NavigationEnd)
if (event instanceof NavigationEnd) { ).subscribe(() => {
this.activeLink = event.urlAfterRedirects; // Capture the active route // Update activeLink based on current route
const currentRoute = this.router.url;
if (currentRoute.startsWith('/blog')) {
this.activeLink = '/blog';
} else {
this.activeLink = currentRoute;
} }
}); });
} }
+53 -4
View File
@@ -1,21 +1,70 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import { map } from 'rxjs/operators';
interface Article {
id: number;
title: string;
slug: string;
content: string;
createdAt: string;
updatedAt: string;
views: number;
authorId: number;
authorName: string;
}
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class ArticleService { export class ArticleService {
private apiUrl = 'http://localhost:7020/api/articles'; // Replace with your API endpoint private apiUrl = '/api/articles';
constructor(private http: HttpClient) {} constructor(private http: HttpClient) {}
getArticles(token: string): Observable<any[]> { getAllArticles(): Observable<Article[]> {
return this.http.get<any[]>(this.apiUrl, { return this.http.get<Article[]>(this.apiUrl);
}
getArticleBySlug(slug: string): Observable<Article |undefined> {
return this.http.get<Article[]>(this.apiUrl).pipe(
map((articles) => articles.find((article) => article.slug === slug))
);
}
getArticleById(id: number): Observable<Article |undefined> {
return this.http.get<Article[]>(this.apiUrl).pipe(
map((articles) => articles.find((article) => article.id === id))
);
}
postArticle(token: string, title: string, content: string ): Observable<any[]> {
return this.http.post<any[]>(this.apiUrl, {
title,
content
},{
headers: { headers: {
'Authorization': `Bearer ${token}` 'Authorization': `Bearer ${token}`
} }
}); });
} }
deleteArticle(id: number, token: string): Observable<boolean> {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
return this.http.delete<any>(`${this.apiUrl}/${id}`, { headers }).pipe(
map((response) => {
// If the backend responds successfully, return true
return !!(response && response.message === 'Article deleted');
})
);
}
editArticle(id: number, token: string | null, title: string, content: string): Observable<any> {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
const body = { title, content };
return this.http.put<any>(`${this.apiUrl}/${id}`, body, { headers });
}
} }
+1 -1
View File
@@ -7,7 +7,7 @@ import {Observable, tap} from 'rxjs';
}) })
export class AuthService { export class AuthService {
private apiUrl = '/api/auth/login'; // Replace with your API endpoint private apiUrl = '/api/auth/login';
constructor(private http: HttpClient) {} constructor(private http: HttpClient) {}
+31
View File
@@ -0,0 +1,31 @@
import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Meta } from '@angular/platform-browser';
@Injectable({
providedIn: 'root'
})
export class UpdateMetaService {
constructor(private titleService: Title, private metaService: Meta) {}
updateMetaTags(meta: { title?: string; description?: string; image?: string; url?: string; color?: string }) {
if (meta.title) {
this.titleService.setTitle(meta.title);
this.metaService.updateTag({ name: 'og:title', content: meta.title });
}
if (meta.description) {
this.metaService.updateTag({ name: 'description', content: meta.description });
this.metaService.updateTag({ name: 'og:description', content: meta.description });
}
if (meta.image) {
this.metaService.updateTag({ name: 'og:image', content: meta.image });
}
if (meta.url) {
this.metaService.updateTag({ name: 'og:url', content: meta.url });
}
if (meta.color) {
this.metaService.updateTag({ name: 'theme-color', content: meta.color });
}
}
}