Search code examples
angulartypescriptcastingangular2-http

Angular 2.0 And Http request. Cast objects. Error of casting


I have simple class in TS:

export class TestObj
{
  public name:string;
  public id:number;
  public example:string;

}

And simple service:

@Injectable()
export class SimpleService
{
    private testObj:TestObj = new TestObj();

    public constructor(@Inject(Http) private http:Http){}

public getTestObj():void
{

this.http.get("/rest/test2").map(res =>  res.json())
      .do(data => console.log(<TestObj> data))
      .catch(resp => Observable.throw(resp.json().error))

      .subscribe(tobj => {
      this.tobj = tobj;
      console.log(this.tobj);
      }, error => {log.error(error)})

}

If I will print in console log SimpleService.testObj before getTestObj(), I saw

<TestObj>

, but if I will run getTest, log will be

<Object>
<Object>

Is it angular bug? Or Typescript bug?


Solution

  • The problem with your code is that objects returned by your http request are a plain JSON objects without any type information attached. The fact that you cast it to <TestObj> allows only compile time checks to be run smoothly but does not change the actual type of the object that is still Object.

    So if you want to have actual instance of the TestObj in memory - you will have to construct it manually from the received JSON object. Naitive javascript JSON deserialization unfortunately does not provide this possibility. Here are some more info on the subject: link