Angular 4 Display JSON Data from HTTP Request Request

I have a simple Angular 4 application that communicates with an HTTP REST server, and that server just returns the JSON payload, and I would like to display this JSON payload, as in a browser. This is my makeRequest typescript function:

import { Component, OnInit } from '@angular/core';
import {Http, Response} from '@angular/http';

@Component({
  selector: 'app-simple-http',
  templateUrl: './simple-http.component.html'
})
export class SimpleHttpComponent implements OnInit {
  data: string;
  loading: boolean;

  constructor(private http: Http) {
  }

  ngOnInit() {
  }

  makeRequest(): void {
    this.loading = true;
    this.http.request('http://jsonplaceholder.typicode.com/posts/1')
    .subscribe((res: Response) => {
      this.data = res.json();
      this.loading = false;
    });
  }
}

Calling http://jsonplaceholder.typicode.com/posts/1 returns me the following JSON:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Now I show this in my html component as:

<h2>Basic Request</h2>
<button type="button" (click)="makeRequest()">Make Request</button>
<div *ngIf="loading">loading...</div>
<pre>Data Obtained is: {{ data }}</pre>

But in the browser, I see this:

enter image description here

How to make my JSON display as?

+6
source share
2 answers

You can use json pipe . In your template:

<pre>Data Obtained is: {{ data | json }}</pre>

data any string.

+7

:

  • JsonPipe (this.data any):

    <pre>Data Obtained is: {{ data | json }}</pre>

  • JSON :

    this.data = JSON.stringify(res.json()); //data is a string :)

    <pre>Data Obtained is: {{ JSON.stringify(data) }}</pre>

, .toString(), (- {key: value}) [object Object]

, app.ts, ajax json pipe.

+4

All Articles