import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { BehaviorSubject } from 'rxjs'; import { Project } from '../shared/models/project.model'; @Injectable({ providedIn: 'root' }) export class ProjectsService { private _allProjects = new BehaviorSubject>([]); readonly allProjects$ = this._allProjects.asObservable(); private set allProjects(projects: Array) { this._allProjects.next(projects); } private get allProjects(): Array { return this._allProjects.getValue(); } private _currentProject = new BehaviorSubject(null); readonly currentProject$ = this._currentProject.asObservable(); private set currentProject(project: Project) { this._currentProject.next(project); } private get currentProject(): Project { return this._currentProject.getValue(); } private _apiErrored = new BehaviorSubject(false); readonly apiErrored$ = this._apiErrored.asObservable(); private set apiErrored(errored: boolean) { this._apiErrored.next(errored); } private get apiErrored(): boolean { return this._apiErrored.getValue(); } /** * I am actively avoiding any kind of environment management, this is a very basic site and currently this is the only api call. */ private PROJECT_API_URL = "https://cms.inkletblot.com" constructor(private http: HttpClient, private router: Router) { } httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) }; getProjects(): void { this.http .get(`${this.PROJECT_API_URL}/posts`, this.httpOptions) .subscribe( (response: Project[]) => { if (response) { // using text/plain so as to not get the preflight options request // as such : Project[] does not work as expected and objects must be parsed. this.allProjects = response; // filter out different categories here currently only one } }, (error) => { this.apiErrored = true; } ); } getSingleProject(id: string): void { this.http .get(`${this.PROJECT_API_URL}/post/${id}`, this.httpOptions) .subscribe( (response: Project) => { if (response) { // using text/plain so as to not get the preflight options request // as such : Project[] does not work as expected and objects must be parsed. this.currentProject = response; // filter out different categories here currently only one } }, (error) => { this.apiErrored = true; this.router.navigate(['not-found']) } ); } /** * This is not very efficient code but I'm not planning on having that many projects and (if this turns into a blog) blog posts * If this does become a general blog, then I will make this a bit more efficient. * @param id slug of project to get */ getProject(id: string): void { let found = false; this.allProjects.forEach((project) => { if (project.slug === id) { found = true; this.currentProject = project; } }) if (!found) { this.getSingleProject(id) } } }