Circumvent "object property does not exist" error

Asked

Viewed 1,166 times

0

I have the following problem, always time to deal with the result of the request http in the subscribe points out errors saying the 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 property error but she won’t show up until I make the requisition! but I did not understand the logic of this error, and every time having compiled the error project, then I need to comment the lines of all functions that make operation with the result, compile the program, it works, I remove the comment it continues working normal, I do not know if it is angular bug or I am doing something wrong, how to escape from this problem? I don’t know if it’s because of the visual studio code that has such directives: // tslint:disable-next-line:component-class-suffix that removes error marks etc, anyway, any idea?

  • You must type the answer, or assign the result to a type any variable before accessing the property

1 answer

1


Cause of the problem

According to the section Type-checking the Response of the official documentation of framework:

The HttpClient.get() method parse the JSON server Response into the Anonymous Object type. It doesn’t know what the Shape of that Object is.

Translating:

The method HttpClient.get() analyzes the JSON server response and turns it into the anonymous type Object. He doesn’t know the shape of this object.

This means that you cannot access the properties of such an object using point notation unless you explicitly specify the type of the answer.


Solution 1

Use square bracket notation to extract values.

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

Solution 2

Tell the HttpClient the type of answer 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.get().

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

Solution 3

Use the generic type any.

return this.http.get('url').subscribe((result: any) => {
    if (result.error) { // faça alguma coisa };
});
  • perfect solution! thank you! (result: any)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.