Advertisement
Guest User

Untitled

a guest
Dec 18th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { environment } from './../../../../environments/environment';
  2. import { Observable } from 'rxjs';
  3. import { HttpClient } from '@angular/common/http';
  4. import { LinksModel } from './../../models/links/links.model';
  5. import { Injectable } from '@angular/core';
  6.  
  7. @Injectable({
  8.   providedIn: 'root'
  9. })
  10. export class LinksService {
  11.  
  12.   links: LinksModel[];
  13.  
  14.   constructor(
  15.     private http: HttpClient,
  16.   ) {}
  17.  
  18.  
  19.   /**
  20.    * method to be use when calling api for HATEOAS
  21.    * @param type (i.e. authentication, user, usergroup etc.)
  22.    * @param rel relative
  23.    * @param payload
  24.    */
  25.   action<T>(type: string, rel: string, payload?: any): Observable<T> {
  26.     this.links = JSON.parse(localStorage.getItem('links'))[type];
  27.     const link = this.links.find(l => String(l.rel).toLowerCase() === rel.toLowerCase());
  28.     const url = link.href;
  29.     const method = link.method;
  30.  
  31.     switch (method) {
  32.       case 'GET': {
  33.         return this.http.get<T>(`${environment.link}` + url);
  34.       }
  35.       case 'PUT': {
  36.         return this.http.put<T>(`${environment.link}` + url, payload);
  37.       }
  38.       case 'POST': {
  39.         return this.http.post<T>(`${environment.link}` + url, payload);
  40.       }
  41.       case 'DELETE': {
  42.         return this.http.delete<T>(`${environment.link}` + url);
  43.       }
  44.     }
  45.   }
  46.  
  47.   /**
  48.    * responsible for adding links to localstorage
  49.    * @param type (i.e. authentication, user, usergroup etc.)
  50.    * @param links list of links
  51.    * @return void
  52.    */
  53.   addLinks(type: string, links: LinksModel[]) {
  54.     // check if links not exist
  55.     if (localStorage.getItem('links') === null) {
  56.       const data = { [type]: links };
  57.       localStorage.setItem('links', JSON.stringify(data));
  58.     } else {
  59.       // insert type into the links
  60.       const link = JSON.parse(localStorage.getItem('links'));
  61.       link[type] = links;
  62.       localStorage.setItem('links', JSON.stringify(link));
  63.     }
  64.   }
  65.  
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement