Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 HTTP display JSON specific values

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

{{data | json}} is returning all the data.

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

{{data.title | json}} but this doesn't work.

What is the right way to display just the title?

like image 957
Satch3000 Avatar asked Sep 17 '26 21:09

Satch3000


1 Answers

Use elvis operator like this

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

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

like image 52
yurzui Avatar answered Sep 20 '26 11:09

yurzui