繁体   English   中英

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

[英]Angular 4 Display JSON Data from HTTP Get Request

我有一个简单的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;
    });
  }
}

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"
}

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

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

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

在此输入图像描述

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

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

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

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

您有两种选择:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM