0

I have an Angular 8 application with the following code:

export class ResponseModel<T> {
   status: string;
   message: string;
   data: T;

   isSuccess(): boolean {
      return '00' === status;
   }

}

and the following...

this.httpClient.get(myUrl)
  .subscribe((response: ResponseModel<any>) => {

    if (response.isSuccess()) {
        // Rest of the code
    }
}

The response: ResponseModel object serializes well from the http result but response.isSuccess() throws an error:

TypeError: response.isSuccess() is not a function 

What could be wrong with my code above?

Kihats
  • 3,326
  • 5
  • 31
  • 46

1 Answers1

3

By declaring response: ResponseModel<any>, you are telling the Typescript compiler that you expect response to be of the type ResponseModel<any>, or at least conform to its interface. Declaring the type doesn't automatically make it an instance of that type.

ResponseModel<T> is a class that you have created - the http client knows nothing about it.

response is some object. You need to create an instance of ResponseModel<T> from response if you want an instance of it.

this.httpClient.get(myUrl).pipe(
  map((response: any): ResponseModel<any> => {
    const response = new ResponseModel<any>();
    // TODO: set the properties
    response.status = response.status;
    return response;
  })
).subscribe((response: ResponseModel<any>) => {
    if (response.isSuccess()) {
        // Rest of the code
    }
}
Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
  • 1
    This one worked. Though, to avoid setting all properties one by one, one can use `const rsp = Object.assign(new ResponseModel(), response);` – Kihats Mar 29 '20 at 14:58
  • Correct. The crux of your problem was not creating an instance of the class - I didn't want to get bogged down in the various ways you can set the properties. Personally, I prefer to keep control over what properties I'm setting. `Object.assign` will copy all properties across, regardless of whether or not they're declared on the class. – Kurt Hamilton Mar 29 '20 at 15:02