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
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.
And then you can easily inject this service into your other files.
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 aroundHttpClient
.However, if there is need of some additional logic, it might be possible that Angular HTTP interceptors will be a better fit.