无法将 sort() 与 HttpClient 订阅一起使用,“Object”类型上不存在属性“sort”

pre*_*vox 1 sorting http httpclient typescript angular

我正在从 Http 转移到 HttpClient,但现在我无法使用 map() 对结果进行排序,因此出现了一些错误。

使用 HttpClient,我得到“对象”类型上不存在属性“排序”。

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;
});
Run Code Online (Sandbox Code Playgroud)

使用 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;
});
Run Code Online (Sandbox Code Playgroud)

Deb*_*ahK 6

res我只需指定as的类型就可以让它工作[]

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;
});
Run Code Online (Sandbox Code Playgroud)

然后代码就知道 res 是一个数组,并且数组有一个sort方法。

如果您为数组定义了接口,那么最好使用它。例如:

(res:IConcept[]) => { ... }
Run Code Online (Sandbox Code Playgroud)

  • 无论如何,这不应该是公认的答案。使用any[]是告诉类型系统基本上忽略你正在输入的任何内容,就此而言你可以使用any。请阅读对您的问题的评论。 (2认同)