1

I am trying to follow these directions: https://angular.io/docs/ts/latest/guide/server-communication.html and get the list of objects from the server in form of an object (not json).

I have a model class (simplified for now):

export class Goal {
  id: number;
  title: string;
}

And I am trying to get list of these from the server through a service class as follows:

export class GoalsService {

  constructor(public authHttp:AuthHttp) {
  }

  getGoals() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
      .map(res => {
          <Goal[]> res.json()
        }
      )
      .do(data => console.log(data))
      .catch(this.handleError);
  }
...

And the client using the service class is:

loadGoals() {
    this.goalsService.getGoals().subscribe(
      goals => this.goals = goals
    );
  }

The request goes through properly and I am getting back:

[{"id":1,"title":"target"}]

However, in the client, inside subscribe, goals variable is always 'undefined'.

I tried debugging it, this is what I get: enter image description here

Which says to me that json received and parsed properly, but casting it into a target object is not working (unless I am not fully getting the mechanism).

What am I doing wrong?

Thanks,

Note: the authHttp service that I use is this guy: https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/. And it works in all other places as expected. So I doubt that it is a peoblem.

1 Answer 1

3

As you are using map arrow function, you should return mapped result.

return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
  .map(res => {
      return <Goal[]> res.json(); //return mapped object from here
    }
)

OR

return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
  .map(res => <Goal[]> res.json()) //or simply do map object directly
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Works! I'll accept the answer in 4 minutes :)
@ShurikAgulyansky Glad to help you. Thanks :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.