我在 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
关于Angular 2.0 和 Http 请求。类型转换物体。类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427458/