Angular 2 - Http explanation needed

Hello,

Im working through a little project of mine and I’m bit confused with few lines of code and could use some with clarification.

I stripped down the code just to make things clear. Looking at service.ts snippet you can see i have the following line of code .map((res: Response) => res.json()) … according to the tutorials I looked at indicate that this line converts the data coming in to j Json format".

now looking at the component.ts and more specifically the line: data1 => this.projectList = data1;
this line assigns the results to this.projectList.

question:

  1. Am i correct in assuming that in service.ts the data is return in json format?
  2. why can’t I display the array as such {{this.projectList}} or {{this.projectList | josn}}. it appears as objects.
  3. If i do this → JSON.stringify(this.projectList) now i can dispay the data but I thought it was already converted to json?

what am i missing?

service.ts

 onButtonClickMethod(): Observable<any>{       
        let headers = new Headers({'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });                
      
        return this._http
                .post(this.userUrl, options)
                .map((res: Response) =>  res.json())                
                .catch (this.handleError);
    }

component.ts

.subscribe(
	data1 => 	this.projectList = data1;			
        console.log('returned Data: ' + JSON.stringify(this.projectList));							
	

Hey @robin01,

When you make a request to an endpoint that responds with JSON, you still actually get that data back as text, which has to be parsed and converted into JavaScript objects. This is what happens when you call .json() on the response object.

Calling JSON.stringify() converts the JavaScript objects back into a string of JSON, which is handy if you want to output them for debugging.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.