Angular 2 HTTP显示JSON特定值 [英] Angular 2 HTTP display JSON specific values

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

问题描述

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

I have this code which reads some json data:

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"
}

{{数据|json}} 返回所有数据.

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

I wanted to just get the title for example. So I tried this:

{{data.title |json}} ,但这是行不通的.

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

What is the right way to display just the title?

推荐答案

使用像这样的猫王运算符

Use elvis operator like this

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

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

The Elvis operator (?) means that the data field is optional and if undefined, the rest of the expression should be ignored.

这篇关于Angular 2 HTTP显示JSON特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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