Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //SERVICE
- import { Injectable } from '@angular/core';
- import { Categoria } from '../_type/categoria.type';
- import { Libro } from '../_type/libro.type';
- import { ChiamataHTTP } from '../_type/chiamataHTTP.type';
- import { HttpClient } from '@angular/common/http';
- import { from, Observable, Subscriber } from 'rxjs';
- import { IRispostaServer } from '../_interface/IRispostaServer.interface';
- @Injectable({
- providedIn: 'root'
- })
- export class ApiService {
- constructor(private http:HttpClient) { }
- /**
- *
- * @param risorsa(string|number)[]
- * questo array definisce la risorsa della collection oppure l'elemento specifico
- * della risorsa
- * La funzione calcola l'url dell'api dove X e' il nome dell'api(in questo esempio CATEGORIE)
- * @returns string stringa che rappresenta l'endpoint del server
- */
- protected calcolaRisorsa(risorsa: (string | number)[]):string{
- const server: string ='http://localhost:8000/api' //path della route
- const versione:string='v1' //versione della route
- let url= server+'/'+ versione+ '/'
- risorsa.forEach(x=>{url=url+x+'/'})
- return url
- }
- /**
- * Questa funzione definisce il tipo di risposta a seconda del tipo di richiesta fatta
- * @param risorsa (string|number)[] risorsa di cui voglio sapere i dati(nome dell'api)
- * @param tipo string GET|POST|PUT|DELETE tipo di chiamata HTTP
- * @param parametri OBJECT|NULL paramentri da passare all'endpoint se e' di tipo (POST|PUT)
- * @returns Observable
- */
- protected richiestaGenerica(risorsa: (number | string)[], tipo: ChiamataHTTP, parametri?: Object | null):Observable<IRispostaServer>{
- //uso una funzione per calcolare l'url
- const url=this.calcolaRisorsa(risorsa)
- //Qui vado a definire la risposta a seconda del tipo di richiesta
- switch (tipo) {
- case 'GET': return this.http.get<IRispostaServer>(url)
- break;
- case 'POST': if(parametri!==null){
- return this.http.post<IRispostaServer>(url,parametri)
- }else{
- const objErrore = { data: null, message: null, error: 'NO_PARAMETRI_PASSATI' };
- return from([objErrore]);
- //Verisone modificata del prof
- // const obs$=new Observable<IRispostaServer>(Subscriber=>Subscriber.next(objErrore))
- // return obs$
- }
- break;
- // case 'PUT':
- // break;
- // case 'DELETE':
- // break
- default: return this.http.get<IRispostaServer>(url)
- break
- }
- }
- //GET
- /**
- * Funzione per richiamere tutte le categorie (ossia l'effettiva chiamata all'api)
- * @returns Observable
- */
- public getCategorie(): Observable<IRispostaServer> {//NELLA LEZIONE SI CHIAMA getTipologieIndirizzi()
- const risorsa: string[] = ['categorie'] //'endpoint che voglio ottenere
- return this.richiestaGenerica(risorsa,'GET')
- }
- /**
- * Funzione per richiamere la categoria singola (ossia l'effettiva chiamata all'api)
- * @returns Observable
- */
- public getCategoria(id: string): Observable<IRispostaServer> {//NELLA LEZIONE SI CHIAMA getTipologiaIndirizzo()
- const risorsa: string[] = ['categoria',id] //'endpoint che voglio ottenere
- return this.richiestaGenerica(risorsa, 'GET')
- }
- //POST
- public postCategoria(paramentri: Partial<Categoria>): Observable<IRispostaServer> {//Il prof la chiama postTipologiaIndirizzo()
- const risorsa: string[] = ['inserisci/categoria']
- return this.richiestaGenerica(risorsa, 'POST', paramentri)
- }
- }
- //TS DEL COMPONENT
- import { Component, OnDestroy, OnInit } from '@angular/core';
- import { map, Subject, take, takeUntil, tap } from 'rxjs';
- import { ApiService } from 'src/app/_service/api.service';
- import { Categoria } from 'src/app/_type/categoria.type';
- @Component({
- selector: 'app-richiesta-http-post',
- templateUrl: './richiesta-http-post.component.html',
- styleUrls: ['./richiesta-http-post.component.scss']
- })
- export class RichiestaHttpPostComponent implements OnInit,OnDestroy {
- private distruggi$=new Subject<void>()
- //Questo subject si attivera' alla distruzione della classe
- private osservatore={
- next:(x:Categoria)=> console.log("Il valore passato e':",x),//essendo preso da x.data sara' di tipo Categoria
- error:(err:string)=>console.log(err),
- complete:()=>console.log('Completato')
- }
- constructor(private api:ApiService){}
- ngOnInit(): void {}
- ngOnDestroy(): void {
- this.distruggi$.next()
- }
- aggiungiValore(){
- console.log('aggiungi Valore')
- const parametro:Partial<Categoria>={nome:'IndProva'}
- this.api.postCategoria(parametro)
- this.obsAddCategoria(parametro).subscribe(this.osservatore)
- }
- obsAddCategoria(dati: Partial<Categoria>) {
- return this.api.postCategoria(dati).pipe(
- tap(x => console.log('Risposta API:', dati)), // Logga tutta la risposta
- take(1),
- map(x => x.data),
- takeUntil(this.distruggi$)
- );
- }
- }
- //HTML
- <h1 class="text-danger">Richiesta HTTP POST fatta dal professore</h1>
- <hr>
- <button type="button" class="btn btn-warning" (click)="aggiungiValore()">Aggiungi Valore</button>
- <hr>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement