【问题标题】:Angular 2 HTTP display JSON specific valuesAngular 2 HTTP 显示 JSON 特定值
【发布时间】:2019-04-03 22:36:44
【问题描述】:

我有这段代码可以读取一些 json 数据:

import {Component} from 'angular2/core';
import {Http, Response} from 'angular2/http';

@Component({
    selector: 'my-app',
    template: `
      <h2>Basic Request</h2>
      <button type="button" (click)="makeRequest()">Make Request</button>
      <div *ngIf="loading">loading...</div>
      <pre>{{data | json}}</pre>

    `

})
export class AppComponent {

    data: Object;
    loading: boolean;

    constructor(public http: Http) {
    }
    makeRequest(): void {
        this.loading = true;
        this.http.request('http://jsonplaceholder.typicode.com/photos/1')
            .subscribe((res: Response) => {
                this.data = res.json();
                this.loading = false;
            }); }

}

This is the returned json:

{
  "albumId": 1,
  "id": 1,
  "title": "accusamus beatae ad facilis cum similique qui sunt",
  "url": "http://placehold.it/600/92c952",
  "thumbnailUrl": "http://placehold.it/150/30ac17"
}

{{data | json}} 正在返回所有数据。

例如,我只想获得标题。 所以我尝试了这个:

{{data.title | json}} 但这不起作用。

只显示标题的正确方法是什么?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    像这样使用猫王运算符

    <pre>{{data?.title}}</pre>
    

    Elvis 运算符 (?) 表示数据字段是可选的,如果未定义,则应忽略表达式的其余部分。

    【讨论】:

      【解决方案2】:

      添加地图并切换获取

         this.data = {}; //initialize to empty object
         this.http.get('http://jsonplaceholder.typicode.com/photos/1')
                  .map((res: Response) => res.json())
                  .subscribe(res => {
                      this.data = res;
                      this.loading = false;
                  });
      

      然后在模板中这样使用{{data.title}}

      这里还有一些 http 示例:http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

      【讨论】:

      【解决方案3】:

      数据是一个 JSON 对象,所以如果你使用数据,那么使用 | json 管道。 如果要使用不是 Object 的值,则直接使用该值

      {{data.title}}
      

      【讨论】:

      • 这不会返回任何东西......编辑说:未解决的变量标题
      • 我也有同样的问题。只需在 html 代码中编写对象就会在视图中打印“[object Object]”。尝试获取任何属性会导致“EXCEPTION: TypeError: l_fav0 is undefined in [null]”,其中“fav”是我的对象的名称。我不知道我错过了什么,但它与 Satch3000 有同样的问题。全网只是给出相同的建议,没有任何帮助,除了太简单的例子外,找不到任何例子。
      【解决方案4】:

      你可以试试这个

       this._http.request('http://jsonplaceholder.typicode.com/photos/1' )
                  .map((res:Response) => res.json()) //add this line
                  .subscribe(
                      data => this.myData = data,
                      this.loading = false;
                      error =>this.logError(error),
                  );
      

      你现在可以{{myData.title}}

      对于多个对象使用:ngFor like this

      <li *ngFor="let item of myData">
              {{item.title}}
          </li> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多