I am facing an issue with the following code:
public fetchResults(searchTerm: string): Observable<Array<SearchResult>> {
let params = new HttpParams().set('searchTerm', searchTerm);
return this.http
.get<Array<SearchResult>>(this.apiUrl, { params: params })
.map((results: SearchResult[]) => results.map((r: SearchResult) => new SearchResult(r)));
}
The problem lies in the fact that the API response is a JSON object which doesn't match the structure of my TypeScript class. Despite this mismatch, I want to utilize the properties defined within the TypeScript class.
Can anyone suggest a more efficient way to transform the array fetched from the API call into an array comprised of instances of SearchResult
?
Below is the definition of the SearchResult
object:
import { Name } from './name';
export class SearchResult {
public id: string;
public name: Name;
public dateOfBirth: Date;
public socialSecurityNumber: string;
public get info(): string {
let result: string = `${this.name}`;
if (this.dateOfBirth)
result += ` | ${this.dateOfBirth.toLocaleDateString()}`;
return result;
}
constructor(data: SearchResult) {
this.id = data.id;
this.name = new Name(data.name);
this.dateOfBirth = data.dateOfBirth? new Date(data.dateOfBirth) : undefined;
this.socialSecurityNumber = data.socialSecurityNumber;
}
public toString(): string {
return this.info;
}
}