0

Coming from a C# background, I'd thought this should work in typescript. I have a class which contains a read-only property that depends on other two properties in the class.

export class Foo {
   bar1: number;
   bar2: number;
   get bar3(): boolean {
      return this.bar1 > this.bar2;
   }
}

Now in Angular 4 I have a service returning Observable e.g.

getFoos(fooId: number): Observable<Foo[]> {
        return this.http.get(this.url)
            .map((res: Response) => res.json());
    }

Note that my REST api response does NOT return bar3 but only bar1 and bar2. Then in my component, when trying to access Foo[], its entry doesn't have bar3 property on it, only bar1 and bar2. So how to make bar3 populated?

dragonfly02
  • 3,403
  • 32
  • 55
  • You have to create Foo object with new keyword otherwise all methods will not exist – MistyK Oct 07 '17 at 17:08
  • An array of objects, parsed from JSON, is not automatically converted into an array of `Foo` objects just because they have two of three properties in common with `Foo` – Andreas Oct 07 '17 at 17:10
  • @Andreas @MistyK sounds like you two are saying the same/similar thing; so how does `res.json()` convert to a strongly typed `Observable` then? Does it call `new Foo()` at all? – dragonfly02 Oct 07 '17 at 17:14
  • Possible duplicate of [How do I cast a JSON object to a typescript class](https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class) – Andreas Oct 08 '17 at 09:13

1 Answers1

0

According to your comment res.json() gives you type any so there is no check at all. Normally typescript use duck typing to check if your object properties match interface properties. To solve your problem you should either create your object something along these lines:

  getFoos(fooId: number): Observable<Foo[]> {
            return this.http.get(this.url)
                .map((res: Response) => res.json().then(data)=>{
                    return data.map(el=>{
                      let obj = new Foo();
                      return {obj, ...el};
                      }
});
        }

Or follow some suggestions described here: How do I cast a JSON object to a typescript class

MistyK
  • 6,055
  • 2
  • 42
  • 76