【发布时间】:2017-08-23 11:31:49
【问题描述】:
我有一个简单的 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 按原样显示?
【问题讨论】: