Search code examples
angulartypescriptsortinghttphttpclient

Can't use sort() with HttpClient subscribe, property 'sort' does not exist on type 'Object'


I'm moving from Http to HttpClient but I get some errors now that I can't use map() to sort the result.

With HttpClient I get Property 'sort' does not exist on type '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;
});

with Http I can sort it without problems

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;
});

Solution

  • I was able to get this to work by just specifying the type of 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;
    });
    

    The code then knows that res is an array and an array has a sort method.

    If you have an interface defined for the array, it would be better to use it. For example:

    (res:IConcept[]) => { ... }