Files
codiki-hexagonal/frontend/src/app/pages/my-publications/my-publications.service.ts
2024-09-21 12:20:22 +02:00

57 lines
2.5 KiB
TypeScript

import { inject, Injectable } from "@angular/core";
import { PublicationRestService } from "../../core/rest-services/publications/publication.rest-service";
import { AuthenticationService } from "../../core/service/authentication.service";
import { BehaviorSubject, Observable } from "rxjs";
import { Publication } from "../../core/rest-services/publications/model/publication";
import { Router } from "@angular/router";
import { MatSnackBar } from "@angular/material/snack-bar";
@Injectable()
export class MyPublicationsService {
private readonly authenticationService = inject(AuthenticationService);
private readonly publicationRestService = inject(PublicationRestService);
private readonly snackBar = inject(MatSnackBar);
private readonly router = inject(Router);
private publicationsSubject = new BehaviorSubject<Publication[]>([]);
private isLoadingSubject = new BehaviorSubject<boolean>(false);
private isLoadedSubject = new BehaviorSubject<boolean>(false);
get publications$(): Observable<Publication[]> {
return this.publicationsSubject.asObservable();
}
get isLoading$(): Observable<boolean> {
return this.isLoadingSubject.asObservable();
}
get isLoaded$(): Observable<boolean> {
return this.isLoadedSubject.asObservable();
}
loadAuthenticatedUserPublications(): void {
const authenticatedUser = this.authenticationService.getAuthenticatedUser();
if (authenticatedUser) {
this.isLoadingSubject.next(true);
this.isLoadedSubject.next(false);
const query = `author_id=${authenticatedUser.id}`;
this.publicationRestService.search(query)
.then(publications => {
this.publicationsSubject.next(publications);
})
.catch(error => {
const errorMessage = $localize`An error occurred while retrieving your publications...`;
this.snackBar.open(errorMessage, $localize`Close`, { duration: 5000 });
console.error(errorMessage, error);
})
.finally(() => {
this.isLoadingSubject.next(false);
this.isLoadedSubject.next(true);
});
} else {
this.authenticationService.unauthenticate();
this.snackBar.open($localize`You are unauthenticated. Please, log-in first.`, $localize`Close`, { duration: 5000 });
this.router.navigate(['/login']);
}
}
}