1

I have a class in typescript which is like below :

    export class Broker {
    constructor() {
        this.id = Guid.newGuid();
        this.stations = new Array<Station>();
    }
    index: number;
    id: string;
    name: string;  
    stations: Array<Station>;
    isIncomplete(): boolean { // error occurs because of this function which is undefined
        if (this.name == "" || this.name == undefined)
            return true;      
        return false;
    }
}

and an array of this class

brokers: Array<Broker>;

I get the brokers from server like below

ngOnInit(): void {

    this.brokers = new Array<Broker>();

    this.brokerservice.getlist().then(
        data => this.brokers = data as Array<Broker>,

        error => this.errorMessage = <any>error);    
}

getlist in service returns the correct type (Array of Broker) and the json which is received from server is like below:

var brokers = new[]
        {

            new
            {
                index = 0,
                id = "097809098008",
                name = "کارگزاری اول",
            },
            new
            {
                index = 0,
                id = "98709-9",
                name = "کارگزاری ",
            },
        };

isIncomplete() function is a calculated function, I can not define (or at least i do not know how) it on server side when I want to use brokers a on client side I got the error isIncomplete is not a function if I omit the function everything works fine. even if I declare the exact type of brokers array and cast it but the error occurs. what is the best way (instead of defining a global function) to solve the problem??

Paridokht
  • 1,374
  • 6
  • 20
  • 45

1 Answers1

1

Easiest way is to use Object.assign if you are targeting ES6:

data => this.brokers = data.map(d => Object.assign(new Broker(), d))

If you are targeting < ES6, then you can use this polyfill from MDN.

Saravana
  • 37,852
  • 18
  • 100
  • 108