I'm wondering if there's a better way to write the ApiService and the CategoryService so that CategoryService is basically just a call to extend ApiService with the string 'category' and the base type 'ICategory' or if this is the best that I can get from typescript and angular? There will be many more endpoint services in the final app
Any other general comments on code style etc are also very welcome (or if anyone knows how to tell Webstorm to not put the constructor closing braces on the next line!!)
ApiService
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
const baseUrl = environment.serverBaseUrl;
const apiEndpoint = environment.apiEndpoint || '/api/v1/';
const apiUrl = `${baseUrl}${apiEndpoint}`;
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {
}
private createTokenOptions() {
return {headers: new HttpHeaders().set('Authorization', `Bearer ${localStorage.getItem('access_token')}`)};
}
get<T>(serviceEndpoint: string, id?: number): Observable<T> {
let url = `${apiUrl}${serviceEndpoint}`;
if (id) {
url += `/${id}`;
}
return this.http.get<T>(url, this.createTokenOptions());
}
create<T>(serviceEndpoint, item: T): Observable<object> {
const options = this.createTokenOptions();
options.headers = options.headers.append('Content-Type', 'application/json');
return this.http.post(`${apiUrl}${serviceEndpoint}`, JSON.stringify(item), options);
}
delete<T>(serviceEndpoint: string, id: number): Observable<T> {
return this.http.delete<T>(`${apiUrl}${serviceEndpoint}/${id}`, this.createTokenOptions());
}
}
CategoryService
import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { Observable } from 'rxjs';
import { ICategory } from '../interfaces/category.model';
@Injectable({
providedIn: 'root'
})
export class CategoryService {
private serviceEndpoint = 'category';
constructor(private api: ApiService) {
}
getCategories() {
return this.api.get<ICategory[]>(this.serviceEndpoint);
}
getCategory(id: number): Observable<ICategory> {
return this.api.get<ICategory>(this.serviceEndpoint, id);
}
createCategory(category: ICategory) {
return this.api.create<ICategory>(this.serviceEndpoint, category);
}
deleteCategory(id: number) {
return this.api.delete<ICategory>(this.serviceEndpoint, id);
}
}