I'm trying to cast a complex (multiple type classes) json response object ( which i receive from my nodejs/mongoose backend) to a typescript class.
A moment class contains an author of type user and a comments array of type comment.
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) {
console.log(data);
if (data) {
this.deserialize(data);
}
}
private deserialize(data: Moment) {
const keys = Object.keys(this);
for (const key of keys) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
}
public get author(): User {
return this._author;
}
public set author(data: User) {
this._author = new User(data);
}
public get comments(): Comment[] {
return this._comments;
}
public set comments(data: Comment[]) {
this._comments = data.map(c => new Comment(c));
}
}
comment.model.ts
export class Comment {
_id?: string = null;
body?: string = null;
moment?: any = null;
author?: any = null;
likes?: any[] = [];
dislikes?: any[] = [];
parent?: any = null;
replies?: any = null;
updated_at?: string = null;
created_at?: string = null;
constructor(data?: Comment) {
console.log(data);
if (data) {
this.deserialize(data);
}
}
private deserialize(data: Comment) {
const keys = Object.keys(this);
for (const key of keys) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
}
}
user.model.ts
export class User {
_id?: string = null
updated_at?: string = null;
created_at?: string = null;
profile?: any = null;
phone?: any = null;
email?: any = null;
followers: any[] = [];
following: any[] = [];
isOnline: any = null;
socketId: any = null;
constructor(data?: User) {
console.log(data);
if (data) {
this.deserialize(data);
}
}
private deserialize(data: User) {
const keys = Object.keys(this);
for (const key of keys) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
}
moment.service.ts
get(moment_id) {
let endpoint = this.path + moment_id;
return this.apiService.get(endpoint)
.map((res) => new Moment(res.data));
}
moment-detail.component.ts
this.route.params.switchMap((params) => {
let moment_id = params['id'];
return this.momentService.get(moment_id);
}).subscribe((res) => {
this.moment = res;
console.log(this.moment);
});
When i call my service i assign the json to a new class of Moment. In the component i then try to print this.moment. Everything is fine except for the author and a comments which are null/empty.
_authoris of typeUserand values will get assigned to members of _author only if you call likenew User( data[key]). Otherwise, because of type compatibility, you will get the error and it gives null which is expected.Moment(withnew Moment) but I don't see the other classes being called anywhere?