Search code examples
angularangular-http

No methods in http response object


Object returned by $http.get has no methods. Example: I have my class model

export class Lab {

    constructor(
        public id: number,
        public name: string,
        public description: string,
        public isActive: boolean,
        public classes: Classes[]
    ) { }

    isActive(lab: Lab) {
        return this.isActive;
    }
}

in my service I call http fetching lab

getLab(labId: number) {
    return this.http.get<Lab>(DidacticsServiceUrls.apiRoot + labId).toPromise();
}

and when I get this in some component, method isActive is undefined, so call

lab.isActive();

throws exception. Is there any clean solution for this?


Solution

  • The server just returns data formed with properties from the defined object. It doesn't actually create an instance of the object.

    Try something like this:

    this.lab = Object.assign(new Lab(), this.retrievedLab)
    

    Where this.retrievedLab is the data returned from the server.

    This should create the object and then copy any of the retrieved properties into it.