将ajax结果分配给包含接口的方法 [英] Assign ajax result to interface inclusive methods

查看:112
本文介绍了将ajax结果分配给包含接口的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新的Typescript,有一点问题,让我的代码工作。我有以下接口/类结构

  interface IInterface {
id:
method():string;
}

class IClass implements IInterface {
id:number;
method():string {returnfoo;}
}

现在我想通过以下调用从web服务获取一些数据

  $。get(/ some / url, data:Array< IInterface>)=> {
for(var i = 0; i console.log(data [i] .id);
console.log(data [i] .method());
}
});

虽然这种编译完全精细的typescript和所有的属性设置完美,我得到一个运行时类型错误 data [i] .method不是一个函数



现在我的问题: ?)

UPDATE 根据请求:转储我获得的数据从webservice。

  data = [{id:1},{id:2},...] 

当然,这是一个简化的例子,真正的类/接口有一些更多的属性(他们都被正确分配)只有一个方法(到目前为止,当我得到它的工作,一些更多的会遵循)。

解决方案

问题是你收到的是符合接口的对象,但它们没有方法属性。



您需要从$ IClass 类型创建新对象,在响应处理程序中扩展数据中的对象:

  $。 get(/ some / url,(data:Array< IInterface>)=> {
return data.map((d)=> return new IClass(d.id));
});


I'm quite new to Typescript and have a bit of a problem to get my code working. I have the following interface/class structure

interface IInterface {
  id : number;
  method() : string;
}

class IClass implements IInterface {
  id : number;
  method() : string { return "foo";}
}

Now I want to get some data from a webservice via the following call

$.get("/some/url", (data : Array<IInterface>) => {
    for (var i = 0; i < data.length; i++) {
        console.log(data[i].id);
        console.log(data[i].method());
    }
});

While this compiles perfectly fine in typescript and also all properties are set perfectly fine, I get a runtime TypeError data[i].method is not a function

So now my question: How can I cast/assign (?) this correctly, so that the methods are also available in the resulting JavaScript?

UPDATE As requested: a dump of the data I get from the webservice.

data = [{id : 1}, {id : 2}, ...]  

Of course, this is a simplified example, the real classes/interfaces have some more properties (they all are assigned correctly), but also only one method (so far, when I get it working, some more will follow).

解决方案

The problem is what you receive are objects which are complying to the interface, but they don't have a method property inside.

What you need to do in order to get this working is, you need to create new objects from type IClass in the reponse handler which extend the objects inside data:

$.get("/some/url", (data: Array<IInterface>) => {
    return data.map((d) => return new IClass(d.id));
});

这篇关于将ajax结果分配给包含接口的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆