I am trying to add a formatting function to my angular model
export class Site {
Id: number;
EstablishedDate: Date;
CreatedDate: Date;
ModifiedDate: Date;
Name: string;
URL: string;
public Format() {
console.log("formatting");
return (this);
}
}
this.API.Get(params['id']).subscribe(
res => {
this.self = res.Format();
}
);
import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Site } from '../../models/site.model';
import { UtilitiesService } from "../utilities/utilities.service";
@Injectable()
export class SitesService {
constructor(private http: HttpClient, private Utils: UtilitiesService) { }
GetAll() {
return this.http.get<Site[]>("/sites/getall");
}
Get(id: string) {
return this.http.get<Site>("/sites/get?id=" + id);
}
}
TypeError: res.Format is not a function
The problem is that res
is not actually of type Site
. It will be a JSON
object that has the data fields of the site class. You can convert the class to an interface that only has the fields, and make the method a function that takes a type of the interface, or you could add a constructor to your class and create a new object from res
The second option would look something like this:
export class Site {
Id: number;
EstablishedDate: Date;
CreatedDate: Date;
ModifiedDate: Date;
Name: string;
URL: string;
public constructor(cfg: Partial<Site>) {
Object.assign(this, cfg);
}
public Format() {
console.log("formatting");
return (this);
}
}
this.API.Get(params['id']).subscribe(
res => {
const site = new Site(res);
this.self = site.Format();
}
);