I have created a customized wrapper class for handling all my http requests. The example provided only includes the get function:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
/**
* Custom HTTP client service for request customization
*/
@Injectable()
export class HttpClientService {
private httpParams: HttpParams;
private httpHeaders: HttpHeaders;
constructor(
private httpClient: HttpClient,
private sharedService: SharedService) {
this.httpParams = new HttpParams();
this.httpHeaders = new HttpHeaders({ 'Access-Control-Allow-Origin': '*' });
}
public get<T>(url: string, httpParams: Array<Map<string, string>>) {
return this.httpClient
.get<T>(url, { params: this.appendHttpParams(httpParams), headers: this.httpHeaders })
.subscribe(data => {
console.log(data);
},
err => {
console.log(err);
});
}
private appendHttpParams(paramArray: Array<Map<string, string>>): HttpParams {
paramArray.forEach((value: Map<string, string>, index: number, array: Array<Map<string, string>>) => {
this.httpParams.append(value.keys[index], value.values[index]);
});
return this.httpParams;
}
}
While this method functions correctly, calling it from a custom service using the following code snippet leads to an error:
this.httpClientService.get<StoredAppData[]>(this.configService.urls.fetchSettings, params)
.map((response) => {
this.storedAppData = response.json();
console.log(this.storedAppData);
return this.storedAppData;
});
The TS2339 error is thrown, stating that Property 'map' does not exist on type 'Subscription'. Removing the .subscribe() would solve this issue, but central error handling on a single layer would then be challenging. What would be a recommended approach to handle this situation?