Unknown developer
Unknown developer

Reputation: 5930

Strange behavior with Observable results in Angular/Typescript

I have the following problem. Imagine a single Angular 2 service:

validate() {
        return this.http.get('api/validate', data); }

When I am trying to consume the above API, everything is Okay with that:

this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result);
        });

and the result is an object:

{status: "success", data: {…}}

However, what will drive me crazy is when I am trying:

this.ValidationService.validate().subscribe(result => {
                console.log('data returned from api', result.data);
            });

Typescript complains there is no data property and there is a compilation error!! At the same time from the following I am getting true...

this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result.hasOwnProperty('data'));
        });

I also tried result['data']. It did not work as well. Any idea about what may happen?

Upvotes: 0

Views: 45

Answers (3)

Eeks33
Eeks33

Reputation: 2315

Try adding an any type for the result like below:

this.ValidationService.validate().subscribe((result:any) => {

You may want to add proper typings for your responses as well, this will make your code more readable and maintainable

Upvotes: 0

Fateh Mohamed
Fateh Mohamed

Reputation: 21377

try this, add ? to prevent errors :

console.log('data returned from api', result?.data);

Upvotes: 0

mickaelw
mickaelw

Reputation: 1513

I think you miss .json() to get the body of the response:

this.ValidationService.validate().subscribe(result => {
  console.log('data returned from api', result.json());
});

If it's that I think it's better to move .json() to your service to don't have many .json() everywhere in your code:

validate() {
  return this.http.get('api/validate', data).map(res => res.json()); 
}

Upvotes: 1

Related Questions