0

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)?

4
  • please elaborate you service part Commented Nov 29, 2017 at 17:58
  • @AnkitKapoor done Commented Nov 29, 2017 at 18:02
  • If you debug then what are you getting in your res object ? Commented Nov 29, 2017 at 18:06
  • Appropriate data. See the edit Commented Nov 29, 2017 at 18:12

1 Answer 1

1

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();                                              
        }
    );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.