Angular 4显示来自HTTP Get Request的JSON数据

spa*_*rkr 9 rest json http angular

我有一个简单的Angular 4应用程序正在联系HTTP REST服务器,这个服务器只是返回一个JSON有效负载,我想在浏览器中显示这个JSON有效负载.这是我的makeRequest打字稿函数:

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;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

http://jsonplaceholder.typicode.com/posts/1的调用会返回以下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"
}
Run Code Online (Sandbox Code Playgroud)

我现在在我的html组件中显示为:

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

但是在浏览器中,我看到了这个:

在此输入图像描述

如何使我的JSON显示为原样?

And*_*aru 20

您可以使用json管道.在您的模板中:

<pre>Data Obtained is: {{ data | json }}</pre>
Run Code Online (Sandbox Code Playgroud)

此外,您必须更改data属性的类型any而不是string.


Pab*_*ano 5

您有两种选择:

  • 使用内置管道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管道的模板。