review-front/src/app/new-post/new-post.component.ts
2024-12-25 22:19:05 +01:00

101 lines
3.2 KiB
TypeScript

import {Component, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../header/header.component';
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {InputTextareaModule} from 'primeng/inputtextarea';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription, switchMap} from 'rxjs';
import {Post} from '../models/post';
import {PostService} from '../services/post.service';
import {CookieService} from 'ngx-cookie-service';
import {MessageService} from 'primeng/api';
import {EditorModule} from 'primeng/editor';
import {AuthorService} from '../services/author.service';
import {Author} from '../models/author';
@Component({
selector: 'app-new-post',
standalone: true,
imports: [
HeaderComponent,
ReactiveFormsModule,
InputTextModule,
InputTextareaModule,
FileUploadModule,
EditorModule
],
templateUrl: './new-post.component.html',
styleUrl: './new-post.component.css'
})
export class NewPostComponent implements OnDestroy {
subs: Subscription[] = []
actualAuthor: Author | undefined;
uploadedFile: File | undefined;
form: FormGroup = new FormGroup({
description: new FormControl('', [Validators.required, Validators.maxLength(512)]),
title: new FormControl('', [Validators.required, Validators.maxLength(50)]),
body: new FormControl('', [Validators.required]),
category: new FormControl('', [Validators.required, Validators.maxLength(50)]),
});
constructor(private postService: PostService,
private cookieService: CookieService,
private authorService: AuthorService,
private messageService: MessageService,) {
this.actualAuthor = JSON.parse(this.cookieService.get("author"));
}
onSelected(event: FileSelectEvent) {
if (event.currentFiles && event.currentFiles.length > 0) {
this.uploadedFile = event.currentFiles[0];
}
}
onSubmit() {
const formData = this.form.value;
if (this.uploadedFile) {
const postToPost: any = { // LOL
body: formData.body as string,
description: formData.description as string,
title: formData.title as string,
category: formData.category as string
};
this.subs.push(
this.postService.createPost(postToPost, this.cookieService.get("token")).pipe(
mergeMap(post =>
this.authorService.attributePost(this.actualAuthor?.id, post.id, this.cookieService.get("token")).pipe(
mergeMap((_) =>
this.postService.changeIllustration(post.id, this.uploadedFile, this.cookieService.get("token"))
)
)
)
).subscribe({
next: () => {
console.log('Post créé, attribué et illustration changée avec succès.');
},
error: (err) => {
this.failureMessage('Erreur', err.message);
}
})
);
}
}
failureMessage(summary: string, detail: string): void {
this.messageService.add({
severity: 'error',
summary: summary,
detail: detail,
life: 3000,
closable: false
});
}
ngOnDestroy(): void {
this.subs.forEach(sub => sub.unsubscribe());
}
}