Angular 2 HTTP显示特定于JSON的值

Angular 2 HTTP display JSON specific values

本文关键字:JSON 的值 HTTP 显示 Angular      更新时间:2023-09-26

我有这样的代码,它读取一些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}},但这不起作用。

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

使用类似的elvis运算符

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

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

添加地图并切换以获取

   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

Data是一个JSON对象,因此如果使用数据,则使用|JSON管道。如果你想使用一个不是Object的值,那么直接使用

{{data.title}}

你可以试试这个

 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>