1

I have the following typescript model:

export class ClaimProvider {
    id: string;
    name: string;

    slug(): string {
        let result = this.name.trim().toLowerCase();
        result = result.toLowerCase();
        result = result.replace(/&/g, '_');
        result = result.replace(/ /g, '_');
        return result;
    }
}

Now in my Angular component I get an API call that populates a local instance of my object:

claimprovider: ClaimProvider;

this.claimProviderService.getCurrentClaimProvider(id)
  .pipe(first())
  .subscribe(
    result => {
      this.claimprovider = result;
      console.log(this.claimprovider);
    }
}

My console.log results show the name and id appropriately so my API call is working.

My problem though is if in the same point I call:

console.log(this.claimprovider.slug())

Then I get an error

ERROR TypeError: _this.claimprovider.slug is not a function

What am I doing wrong?

Edit

This is my getCurrentClaimProvider method:

public getCurrentClaimProvider(claimproviderId): Observable<ClaimProvider> {
    return this.http.get<ClaimProvider>(this.baseUrl + '/GetCurrentClaimProviderHeader?claimproviderid=' + claimproviderId);
}
Robbie Mills
  • 2,705
  • 7
  • 52
  • 87

1 Answers1

3

An Http call such as this:

this.claimProviderService.getCurrentClaimProvider(id)

Maps the result returned from the server to an object with the same properties as the defined interface or class ... but not actual instances of the class.

So you have objects with the id and name properties ... but not actual ClaimProvider instances.

You will have to manually map the returned data to instances of the class.

For an example, you could check this out: Angular - TypeError: Converting circular structure to JSON

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • Deborah, this is really helpful and something I didn't know! Can you point me to more information about this behaviour, or how I can improve my calls? – Robbie Mills Jul 28 '18 at 05:29
  • The link someone provided above may help: https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class – DeborahK Jul 28 '18 at 05:33
  • This may also help: https://stackoverflow.com/questions/36014161/angular2-http-get-cast-response-into-full-object – DeborahK Jul 28 '18 at 05:43