Angular 2.0 和 Http 请求。铸造物体。铸造错误
Angular 2.0 And Http request. Cast objects. Error of casting
我在 TS 中有简单的 class:
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>
是angular错误吗?还是 Typescript 错误?
您的代码存在的问题是您的 http 请求返回的对象是没有附加任何类型信息的普通 JSON 对象。将其强制转换为 <TestObj>
的事实仅允许编译时检查顺利进行 运行 但不会更改对象的实际类型,它仍然是 Object。
因此,如果您想在内存中拥有 TestObj 的实际实例 - 您将必须从接收到的 JSON 对象手动构造它。不幸的是,天真的 javascript JSON 反序列化不提供这种可能性。以下是有关该主题的更多信息:link
我在 TS 中有简单的 class:
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>
是angular错误吗?还是 Typescript 错误?
您的代码存在的问题是您的 http 请求返回的对象是没有附加任何类型信息的普通 JSON 对象。将其强制转换为 <TestObj>
的事实仅允许编译时检查顺利进行 运行 但不会更改对象的实际类型,它仍然是 Object。
因此,如果您想在内存中拥有 TestObj 的实际实例 - 您将必须从接收到的 JSON 对象手动构造它。不幸的是,天真的 javascript JSON 反序列化不提供这种可能性。以下是有关该主题的更多信息:link