我正在从Http迁移到HttpClient,但是我现在遇到了一些错误,因为我不能使用map()对结果进行排序。
使用HttpClient,我得到的属性“sort”在类型“Object”上不存在。
this.getConcept().subscribe(res => {
res.sort((f, n): number => {
if (f.code < n.code) return -1;
if (f.code > n.code) return 1;
return 0;
});
console.error(res);
this.arrConcept = res;
});
字符串
使用Http,我可以毫无问题地排序它。
this.getConcept().map(this.extractData).subscribe(res => {
res.sort((f, n): number => {
if (f.code < n.code) return -1;
if (f.code > n.code) return 1;
return 0;
});
console.error(res);
this.arrConcept = res;
});
型
3条答案
按热度按时间jgzswidk1#
我只需要将
res
的类型指定为[]
,就可以让它工作字符串
然后代码知道res是一个数组,数组有一个
sort
方法。如果你已经为数组定义了一个接口,最好使用它。例如:
型
l3zydbqr2#
.sort是数组或对象的一个属性,你应该相应地输入你的返回值,然后方法就可以使用了。如果你不确定你的方法的返回值,给予它一个any[]。类似于:
字符串
但是最好你应该重写你的方法来返回一个合适类型的数组。另外,输入你的函数的返回值。事实上,如果你想使用typescript,输入所有的东西-这就是typescript的作用!=)
ttisahbt3#
只读
我在尝试
.sort()
一个只读数组时遇到了这个错误。你可以使用.slice()
函数不带参数复制它。在复制的数组上.sort()
工作正常。