Advertisement
Gxbriel_99

Untitled

Mar 24th, 2025
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.09 KB | None | 0 0
  1. //SERVICE
  2. import { Injectable } from '@angular/core';
  3. import { Categoria } from '../_type/categoria.type';
  4. import { Libro } from '../_type/libro.type';
  5. import { ChiamataHTTP } from '../_type/chiamataHTTP.type';
  6. import { HttpClient } from '@angular/common/http';
  7. import { from, Observable, Subscriber } from 'rxjs';
  8. import { IRispostaServer } from '../_interface/IRispostaServer.interface';
  9.  
  10. @Injectable({
  11. providedIn: 'root'
  12. })
  13. export class ApiService {
  14.  
  15. constructor(private http:HttpClient) { }
  16.  
  17. /**
  18. *
  19. * @param risorsa(string|number)[]
  20. * questo array definisce la risorsa della collection oppure l'elemento specifico
  21. * della risorsa
  22. * La funzione calcola l'url dell'api dove X e' il nome dell'api(in questo esempio CATEGORIE)
  23. * @returns string stringa che rappresenta l'endpoint del server
  24. */
  25. protected calcolaRisorsa(risorsa: (string | number)[]):string{
  26. const server: string ='http://localhost:8000/api' //path della route
  27. const versione:string='v1' //versione della route
  28. let url= server+'/'+ versione+ '/'
  29. risorsa.forEach(x=>{url=url+x+'/'})
  30. return url
  31. }
  32.  
  33. /**
  34. * Questa funzione definisce il tipo di risposta a seconda del tipo di richiesta fatta
  35. * @param risorsa (string|number)[] risorsa di cui voglio sapere i dati(nome dell'api)
  36. * @param tipo string GET|POST|PUT|DELETE tipo di chiamata HTTP
  37. * @param parametri OBJECT|NULL paramentri da passare all'endpoint se e' di tipo (POST|PUT)
  38. * @returns Observable
  39. */
  40. protected richiestaGenerica(risorsa: (number | string)[], tipo: ChiamataHTTP, parametri?: Object | null):Observable<IRispostaServer>{
  41. //uso una funzione per calcolare l'url
  42. const url=this.calcolaRisorsa(risorsa)
  43.  
  44. //Qui vado a definire la risposta a seconda del tipo di richiesta
  45. switch (tipo) {
  46. case 'GET': return this.http.get<IRispostaServer>(url)
  47. break;
  48. case 'POST': if(parametri!==null){
  49. return this.http.post<IRispostaServer>(url,parametri)
  50. }else{
  51. const objErrore = { data: null, message: null, error: 'NO_PARAMETRI_PASSATI' };
  52. return from([objErrore]);
  53.  
  54. //Verisone modificata del prof
  55. // const obs$=new Observable<IRispostaServer>(Subscriber=>Subscriber.next(objErrore))
  56. // return obs$
  57.  
  58. }
  59. break;
  60. // case 'PUT':
  61. // break;
  62. // case 'DELETE':
  63. // break
  64. default: return this.http.get<IRispostaServer>(url)
  65. break
  66. }
  67. }
  68.  
  69. //GET
  70.  
  71. /**
  72. * Funzione per richiamere tutte le categorie (ossia l'effettiva chiamata all'api)
  73. * @returns Observable
  74. */
  75. public getCategorie(): Observable<IRispostaServer> {//NELLA LEZIONE SI CHIAMA getTipologieIndirizzi()
  76. const risorsa: string[] = ['categorie'] //'endpoint che voglio ottenere
  77. return this.richiestaGenerica(risorsa,'GET')
  78. }
  79.  
  80.  
  81. /**
  82. * Funzione per richiamere la categoria singola (ossia l'effettiva chiamata all'api)
  83. * @returns Observable
  84. */
  85. public getCategoria(id: string): Observable<IRispostaServer> {//NELLA LEZIONE SI CHIAMA getTipologiaIndirizzo()
  86. const risorsa: string[] = ['categoria',id] //'endpoint che voglio ottenere
  87. return this.richiestaGenerica(risorsa, 'GET')
  88. }
  89.  
  90.  
  91. //POST
  92.  
  93. public postCategoria(paramentri: Partial<Categoria>): Observable<IRispostaServer> {//Il prof la chiama postTipologiaIndirizzo()
  94. const risorsa: string[] = ['inserisci/categoria']
  95. return this.richiestaGenerica(risorsa, 'POST', paramentri)
  96. }
  97.  
  98. }
  99.  
  100. //TS DEL COMPONENT
  101. import { Component, OnDestroy, OnInit } from '@angular/core';
  102. import { map, Subject, take, takeUntil, tap } from 'rxjs';
  103. import { ApiService } from 'src/app/_service/api.service';
  104. import { Categoria } from 'src/app/_type/categoria.type';
  105.  
  106. @Component({
  107. selector: 'app-richiesta-http-post',
  108. templateUrl: './richiesta-http-post.component.html',
  109. styleUrls: ['./richiesta-http-post.component.scss']
  110. })
  111. export class RichiestaHttpPostComponent implements OnInit,OnDestroy {
  112.  
  113. private distruggi$=new Subject<void>()
  114. //Questo subject si attivera' alla distruzione della classe
  115.  
  116. private osservatore={
  117. next:(x:Categoria)=> console.log("Il valore passato e':",x),//essendo preso da x.data sara' di tipo Categoria
  118. error:(err:string)=>console.log(err),
  119. complete:()=>console.log('Completato')
  120. }
  121.  
  122. constructor(private api:ApiService){}
  123.  
  124. ngOnInit(): void {}
  125. ngOnDestroy(): void {
  126. this.distruggi$.next()
  127. }
  128.  
  129. aggiungiValore(){
  130. console.log('aggiungi Valore')
  131. const parametro:Partial<Categoria>={nome:'IndProva'}
  132. this.api.postCategoria(parametro)
  133. this.obsAddCategoria(parametro).subscribe(this.osservatore)
  134. }
  135.  
  136. obsAddCategoria(dati: Partial<Categoria>) {
  137. return this.api.postCategoria(dati).pipe(
  138. tap(x => console.log('Risposta API:', dati)), // Logga tutta la risposta
  139. take(1),
  140. map(x => x.data),
  141. takeUntil(this.distruggi$)
  142. );
  143. }
  144.  
  145. }
  146.  
  147. //HTML
  148. <h1 class="text-danger">Richiesta HTTP POST fatta dal professore</h1>
  149. <hr>
  150. <button type="button" class="btn btn-warning" (click)="aggiungiValore()">Aggiungi Valore</button>
  151. <hr>
  152.  
Tags: angular
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement