My backend service provides me with "moments," and I have two functions to handle this data. One is a get() method that returns a single object, and the other is a search() method that returns an array of objects.
moment.service.ts
The get method successfully maps the response from the backend to create a new instance of my Moment class.
get(moment_id) {
let endpoint = this.path + moment_id;
return this.apiService.get(endpoint)
.map((res) => new Moment(res.data));
}
I want to achieve the same result in the search method, where each object in the array should be a new instance of the Moment class.
search(filters) {
let endpoint = this.path + 'search';
let params = new HttpParams({ fromObject: filters });
return this.apiService.get(endpoint, params)
.map((res) => new Array<Moment>(res));
}
Unfortunately, the above approach does not indicate that the objects in the returned array are of type Moment.
https://i.stack.imgur.com/v0NnA.png
moment.component.ts
moments: Moment[] = [];
this.momentService.search(filters).subscribe((res) => {
this.moments = res;
console.log(this.moments);
});
moment.model.ts
import { Comment } from './comment.model';
import { User } from './user.model';
export class Moment {
_id?: string = null;
body?: string = null;
author?: User = null;
likes?: any[] = [];
dislikes?: any[] = [];
comments?: Comment[] = [];
created_at?: string = null;
updated_at?: string = null;
constructor(data?: Moment) {
if (data) {
this.deserialize(data);
}
}
private deserialize(data: Moment) {
const keys = Object.keys(this);
for (const key of keys) {
if (key === 'author') {
this[key] = new User(data['author']);
} else if (key === 'comments') {
this[key] = data['comments'].map(c => new Comment(c));
} else {
this[key] = data[key];
}
}
}
}