【问题标题】:Angular 4 Display JSON Data from HTTP Get RequestAngular 4 显示来自 HTTP 获取请求的 JSON 数据
【发布时间】: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 按原样显示?

【问题讨论】:

    标签: json angular rest http


    【解决方案1】:

    您可以使用json pipe。在您的模板中:

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

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

    【讨论】:

    • 这仍然没有向我显示整个 JSON!
    • 我仍然只能看到这个:获得的数据是:{"id":1}
    • 如果你做一个console.log(this.data),它是否包含你期望的整个json或者只是在视图中显示的内容?
    • 我把这个console.log(this.data)放在哪里?在我的打字稿文件中?
    • 是的,就在您执行this.data = res.json(); 之后。然后你必须在运行时查看浏览器的控制台窗口。
    【解决方案2】:

    你有两个选择:

    • 使用内置管道 JsonPipe(this.data 应该是 any 类型):

      &lt;pre&gt;Data Obtained is: {{ data | json }}&lt;/pre&gt;

    • 手动获取 JSON 字符串:

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

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

    您必须了解模板中的任何值都是通过调用其.toString() 方法来显示的,因此基本对象(例如{key: value})只显示[object Object]

    【讨论】:

    • 获得的数据是:{"id":1}
    • 奇怪的是我没有看到整个 JSON 消息!
    • 你有什么线索吗?
    • 这意味着这就是你所拥有的,没有理由只显示对象的一部分。使用您的浏览器开发工具检查网络标签
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多