Bypass the error "object property does not exist"

0

I have the following problem, always when processing the result of the request http in subscribe points errors saying that property x does not exist in result

return this.http.get('url').subscribe(result => {
    if (result.error) { // faça alguma coisa };
});

But in fact there is error property, but it will only appear when I make the request! but I did not understand the logic of this error, and every time I have compiled the error project, then I need to comment the lines of all functions that do operation with result , compile the program, work, retreat the comment it continues working normal , I do not know if it's angular bug or I'm doing something wrong, how to escape this problem? I do not know if it is the fault of visual studio code that has a directive like: // tslint:disable-next-line:component-class-suffix that removes error mark etc, anyway, any ideas?

    
asked by anonymous 10.03.2018 / 12:10

1 answer

1

Cause of the problem

According to the Type-checking the response section the official framework documentation:

  

The HttpClient.get() method parse the JSON server response into the   anonymous Object type. It does not know what the shape of that object is   is.

Translating:

  

The HttpClient.get() method parses the response of the JSON server and transforms it into anonymous type Object . He does not know the shape of this object.

This means that you can not access the properties of such an object using dot notation unless you explicitly specify the type of the response.

Solution 1

Use the bracket notation to extract the values.

return this.http.get('url').subscribe(result => {
    if (result['error']) { // faça alguma coisa };
});

Solution 2

Tell%% response type to make output consumption easier and more obvious.

First, define an interface with the correct format:

export interface Resposta {
    error: string;
    // defina propriedades adicionais abaixo
}

Then specify this interface as the type being returned by HttpClient .

return this.http.get<Resposta>('url').subscribe(result => {
    if (result.error) { // faça alguma coisa };
});

Solution 3

Use the generic type HttpClient.get() .

return this.http.get('url').subscribe((result: any) => {
    if (result.error) { // faça alguma coisa };
});
    
10.03.2018 / 15:02