0

I am starting with angular 4 and server side rendering, currently I am trying to get a Proof of Concept fetching some data of one of my external API's. That API return a Json Object.

The site was rendering pretty well, however now that I included the call to fetch data it's not rendered and the response that I am getting doesn't seems to be what I should get.

In the app.components.ts I added:

 private apiUrl= 'https://myapi/Users';
  data: any = {};

  constructor(private http: Http){
    this.getUsers();
    this.getData();
  }

  getData(){
    let res=this.http.get(this.apiUrl).map((res: Response)=>res.json());
    console.log("result:",res)
    return res;
  }

  getUsers(){
    this.getData().subscribe(data=>{
      this.data=data;
    })
  }

Now, as you can see, in the getData method I am printing in console the result of the http calls, however I am getting this:

Observable {
  _isScalar: false,
  source: Observable { _isScalar: false, _subscribe: [Function] },
  operator: MapOperator { project: [Function], thisArg: undefined } }

Why I am not getting there the json object? which could be the reason?

1
  • That is correct. Your res is actually an Observable, not the data itself. Observables are asynchronous. To see the real data, console.log it at your subscribe(). call back function, or you can peek it inside your map call back function. Commented Oct 19, 2017 at 17:13

1 Answer 1

4

Since your getUsers() internally calls getData, you dont have to call again inside the constructor.

constructor(private http: Http){
    this.getUsers();
   //remove this line this.getData();
 }

also place the console.log inside the subscribe method to see the actual data,

getUsers(){
    this.getData().subscribe(data=>{
      this.data=data;
      console.log(this.data);
    })
  }

EDIT As the below comment says, it is not recommended to have your method call inside constructor, make your components to implement ngOnit and add the method inside

Sign up to request clarification or add additional context in comments.

1 Comment

To add to this ... it is not recommended to perform asynchronous operations in the constructor. Instead, use the ngOnInit life-cycle hook method. In addition, it is normally recommended to move data access into its own service. I have a complete example here: github.com/DeborahK/Angular-GettingStarted (in the APM-Final folder)

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.