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([]); private isLoadingSubject = new BehaviorSubject(false); private isLoadedSubject = new BehaviorSubject(false); get publications$(): Observable { return this.publicationsSubject.asObservable(); } get isLoading$(): Observable { return this.isLoadingSubject.asObservable(); } get isLoaded$(): Observable { 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']); } } }