Angular 2.0和Http请求。投射物体。铸造错误

时间:2016-02-16 08:33:00

标签: angular typescript casting angular2-http

我在TS中有简单的类:

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

}

简单的服务:

@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)})

}

如果我将在getTestObj()之前在控制台日志SimpleService.testObj中打印,我看到了

<TestObj>

,但是如果我将运行getTest,则日志将是

<Object>
<Object>

是角虫吗?还是打字稿bug?

1 个答案:

答案 0 :(得分:2)

代码的问题在于,http请求返回的对象是普通的JSON对象,没有附加任何类型信息。将其强制转换为<TestObj>这一事实只允许编译时间检查顺利运行,但不会更改仍为Object的对象的实际类型。

因此,如果您想在内存中拥有TestObj的实际实例,则必须从接收到的JSON对象中手动构造它。不幸的是,Naitive javascript JSON反序列化不提供这种可能性。以下是有关此主题的更多信息:link

相关问题