Angular 4从HTTP获取请求显示JSON数据 [英] Angular 4 Display JSON Data from HTTP Get Request

查看:387
本文介绍了Angular 4从HTTP获取请求显示JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Angular 4应用程序,该应用程序正在与HTTP REST服务器联系,并且该服务器仅返回JSON负载,并且我希望在浏览器中显示该JSON负载.这是我的makeRequest打字稿功能:

I have a simple Angular 4 application which is contacting a HTTP REST server and this server is simply returning a JSON payload and I would like to display this JSON payload as is in the 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;
    });
  }
}

http://jsonplaceholder.typicode.com/posts/1 的呼叫返回了我以下JSON:

The call to 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"
}

我现在在html组件中将其显示为:

I now display 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:

如何使JSON原样显示?

How do I make my JSON displayed as is?

推荐答案

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

You can use the json pipe. In your template:

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

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

Also you have to change the type of your data property to any instead of string.

这篇关于Angular 4从HTTP获取请求显示JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆