Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { environment } from './../../../../environments/environment';
- import { Observable } from 'rxjs';
- import { HttpClient } from '@angular/common/http';
- import { LinksModel } from './../../models/links/links.model';
- import { Injectable } from '@angular/core';
- @Injectable({
- providedIn: 'root'
- })
- export class LinksService {
- links: LinksModel[];
- constructor(
- private http: HttpClient,
- ) {}
- /**
- * method to be use when calling api for HATEOAS
- * @param type (i.e. authentication, user, usergroup etc.)
- * @param rel relative
- * @param payload
- */
- action<T>(type: string, rel: string, payload?: any): Observable<T> {
- this.links = JSON.parse(localStorage.getItem('links'))[type];
- const link = this.links.find(l => String(l.rel).toLowerCase() === rel.toLowerCase());
- const url = link.href;
- const method = link.method;
- switch (method) {
- case 'GET': {
- return this.http.get<T>(`${environment.link}` + url);
- }
- case 'PUT': {
- return this.http.put<T>(`${environment.link}` + url, payload);
- }
- case 'POST': {
- return this.http.post<T>(`${environment.link}` + url, payload);
- }
- case 'DELETE': {
- return this.http.delete<T>(`${environment.link}` + url);
- }
- }
- }
- /**
- * responsible for adding links to localstorage
- * @param type (i.e. authentication, user, usergroup etc.)
- * @param links list of links
- * @return void
- */
- addLinks(type: string, links: LinksModel[]) {
- // check if links not exist
- if (localStorage.getItem('links') === null) {
- const data = { [type]: links };
- localStorage.setItem('links', JSON.stringify(data));
- } else {
- // insert type into the links
- const link = JSON.parse(localStorage.getItem('links'));
- link[type] = links;
- localStorage.setItem('links', JSON.stringify(link));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement