My goal was to develop a versatile REST service that could be utilized across all my services. For instance, for handling POST requests, the following code snippet demonstrates how I implemented it:
post<T>(relativeUrl: string, body?: any, params?: HttpParams, headers?: HttpHeaders): Observable<HttpResponse<T>> {
return this.executeRequest(this.createRequest(relativeUrl, body, params, headers, 'POST'))
}
A similar approach was taken for other HTTP request methods as well. These methods make use of the createRequest and executeRequest functions.
// TODO: Finish and check arguments
private createRequest(relativeUrl: string, body: any, params: HttpParams | null, headers: HttpHeaders | null, method: string ): HttpRequest<any> {
let url: string;
if (relativeUrl.startsWith('http') || relativeUrl.startsWith('https')) {
url = relativeUrl;
} else {
url = `${environment.restUrl}/${relativeUrl}`;
}
headers = headers || new HttpHeaders()
//TODO: If user is logged add Authorization bearer in headers
return new HttpRequest(method, url, body, {
headers: headers,
params: params
})
}
private executeRequest(request: HttpRequest<any>): Observable<HttpResponse<any>> {
return <any> this.http.request(request)
.pipe(
catchError(error => {
return throwError(error);
})
);
}
I have some queries regarding the implementation of these methods. Are they properly structured? Is the response from the HTTP requests handled correctly? As an example, my login.service utilizes the POST method in the following manner:
login<User>(email: string, password: string): Observable<HttpResponse<User>>{
const data = {
email: email,
password: password
};
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Accept-Language': 'it'
})
return this.restService.post<User>(this.baseUrl, data, null, headers)
.pipe(
catchError(error => {
this.notificationService.error(error.error.error.message);
return throwError(error);
})
);
}
One concern relates to the conversion of JSON data returned from the server into my User object. Should this conversion take place within the service or should it be handled by the component utilizing the loginService? Additionally, is it appropriate to perform the conversion using Object.assign(new User(), serverResponse.body)?