skip to Main Content

I have a question that maybe you can help me, I have a service in Angular 17 and I want to make that service obtain all the requests, then, it would be adapted so that it can receive all the requests and return what it needs and thus avoid be doing more services throughout the application. Is this feasible in the future? The following code is an example of what could be

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

 import { Observable } from 'rxjs';

 @Injectable({
 providedIn: 'root'
 })
 export class HttpService {

 constructor(private http: HttpClient) { }

 // Generic method to make GET requests
 get(url: string, params?: any): Observable<any> {
   return this.http.get(url, { params });
 }

 // Generic method to make POST requests
 post(url: string, body: any, options?: any): Observable<any> {
   return this.http.post(url, body, options);
 }

 // Generic method to make PUT requests
 put(url: string, body: any, options?: any): Observable<any> {
   return this.http.put(url, body, options);
 }

 // Generic method to make DELETE requests
 delete(url: string, options?: any): Observable<any> {
   return this.http.delete(url, options);
 }

// Add more methods as needed for other HTTP operations like PATCH etc.
}

control all requests in one

2

Answers


  1. Sure that’s possible, and something I made recently for calling Firebase on a project. I guess you could create whatever abstractions you want in your service.

    @Injectable({
      providedIn: 'root'
    })
    export class HttpService {
      constructor() {}
    
      init() {
        ...
      }
    
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      async post<T = any, U = any>(rpc: string, data: T = undefined, rpcParams: any = {}): Promise<U> {
        return await ...
      }
    
      async get ...
    }
    

    And then you can easily inject this service into your other files.

    export class PageHome {
        constructor(private http: HttpService) { }
    
        async onButtonPress() {
            const res = await this.http.post('my_api', {key: 'value})
        }
    }
    
    
    Login or Signup to reply.
  2. Although, it is absolutely possible, but what’s the point of doing this? Angular HttpClient does exactly the same job, therefore such service without any additional functionality becomes useless wrapper around HttpClient.

    However, if there is need of some additional logic, it might be possible that Angular HTTP interceptors will be a better fit.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search