Aurelia fetch客户端文档有一个获取json数据的基本示例:
bind() {
let client = new HttpClient();
return client.fetch('data.json')
.then(response => response.json())
.then(data => {
console.log(data[1]);
});
}
以上工作正常,但以下情况并非如此:
files = [];
bind() {
let client = new HttpClient();
return client.fetch('data.json')
.then(response => response.json())
.then(files => this.files = files);
}
Gulp现在抱怨"错误TS2322:输入'响应'不能指定为'任何[]'。"
更奇怪的是,我现在在控制台中收到XHR 404错误。这毫无意义; data.json
文件没有找到问题并在第一次获取。第二个代码片段的唯一区别是,我没有将数据记录到控制台,而是实际上尝试用它做一些事情。
答案 0 :(得分:1)
我相信您的具体问题可能是由较旧版本的TypeScript引起的(2.1,最新版本为2.5)。如果您有机会这样做,可以尝试更新它。
语句response
中的 response =>
属于Aurelia定义的Response
类型。当您运行this.files = files
时,似乎TypeScript认为files
属于Response
类型。您已隐式将this.files
声明为any[]
类型,因此不允许进行分配。
您可以通过为files
设置显式类型,甚至只使用any
来解决此问题:
.then((files: any[]) => this.files = files);
我会尽量避免使用any
来解决类型安全问题并使用类型,但是您遇到的问题似乎是TypeScript和/或Aurelia版本中的错误。重新使用。