americanslon americanslon - 11 days ago 117
TypeScript Question

Adding a function to typescript class

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);
}
}


to be then used like so

this.API.Get(params['id']).subscribe(
res => {
this.self = res.Format();
}
);


Here is the service that binds this together

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);
}
}


This compiles fine but I get
TypeError: res.Format is not a function
on execution.

Secondary question - is there a way to trigger that function automatically as object gets populated (akin to c# constructor)?

Answer Source

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();                                              
        }
    );