【发布时间】:2021-03-24 17:48:00
【问题描述】:
在我的 Angular 项目中,我收到此错误:Type '{}' is missing the following properties from type 'any[]'
我有一个简单的角度代码,其中有一个帮助类向 url 发出请求,它发送回一个像 [ {a: b, c: d}, {e: f} ... ] 这样的 JSON 数组,一切正常,具有预期的结果,但是当我尝试将结果返回到主页。
我会继续强制执行该类型,但不知道我可能需要什么来解决此错误并想了解它。
我愿意接受有关代码的问题。
帮助类
export class ExampleJsonGetter{
constructor(private http: HttpClient) {
}
getArray() {
return new Promise((resolve, reject) => {
this.http.post<any>('https://anUrl.com/getjsonarray')
.subscribe({
next: data => {
resolve(data);
},
error: error => {
reject(error);
}
});
});
}
}
主页类
export class MainPage{
variable = [];
constructor(){
example.getArray().then((data)=>{
/*★*/ variable = data; /* ★ */
console.log(variable); // on firefox: 'Array(12): ...' As expected
console.log(typeof variable); // 'object', souldn't it be Array?
}).catch(e=>console.error(e));
}
}
似乎起作用的唯一方法是将★替换为variable = new Array( ...data);
我什至不知道那些三点是做什么的,你能解释一下吗?
【问题讨论】:
-
嗯,我没有得到“替换 *”部分。你在哪里使用
*? -
对于
typeof variable,在JS中数组是一个对象,所以这是正确的。检查变量是否为数组的另一种方法是isArray(): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
三个点(
...)是展开运算符,通常用于扩展可迭代对象的项:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
感谢 @BrunoMonteiro 的名称和对 isArray() 的引用,我需要它。我还尝试使 /* ★ */ 更具可读性
标签: javascript angular typescript