-2

I have an object in javascript:

export class A{

    name:string;

    sayHi() {
      console.log("Hi " + name);
    }

}

I'm filling an array of type A using a backend service, but when I'm going to use sayHi I'm getting that the funcion is not defined:

backService.get().subscribe( (a:A) => a.sayHi());

Now my guess is that since the back end service response is just a Json it does not have a way to actually add the function reference to this object.

How can I define the "sayHi" function inside the A class so it is always available? I could create another class or a static method but I would like to have this logic encapsulated inside the class reference.

Thanks.

Carlos Andres
  • 417
  • 4
  • 13

2 Answers2

2

The way you have it, you need to do something like

let test:A = new A();
test.name = 'Bob';
test.sayHi();

IDK what's going on with your backservice, but it looks like you're assuming get will hydrate an instance of A. If you're just returning the JSON from the backService, then no, it will not have that function. You need code somewhere that's taking the JSON and hydrating an instance of A.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Matt M
  • 1,093
  • 2
  • 11
  • 26
  • Ok. Then I need to create an instance and then assign fill the properties from the backend service, right? Thanks! – Carlos Andres Jan 15 '21 at 14:00
  • Yes. There are libraries that will do this for you called ORMs (object relational mappings). Here is a reddit link on a discussion about ones people use: https://www.reddit.com/r/typescript/comments/98rhh5/what_is_the_recommended_library_for_handling_json/ – Matt M Jan 15 '21 at 14:09
1

I assume you're using RxJs Observables for the backService. If So, you can easily map your json objects to A objects like so:

// dont forget to
import {map} from "rxjs/operators";

export class A{
    name:string;
    constructor(obj: A){ // add constructor (or factory)
       this.name = obj.name;
    }
    sayHi() {
      console.log("Hi " + name);
    }
}

backend
 .get()
 .pipe(
    // map normal objects to instances of A
    map( arr => arr.map( item=>new A(item as any) ) 
 )
 .subscribe( objects => {
    // do whatever
 })
  • the constructor should probably take in an `any` if he's getting JSON back from the service, not an `A` – Matt M Jan 15 '21 at 14:21
  • @MattM yes indeed, I just find it to help the IDE if I declare it this way. Also, I'm not a big fan of the 'any' type. – Omar Abu Saada Jan 15 '21 at 14:24