Satch3000 Satch3000 - 4 months ago 31
AngularJS Question

Angular2 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?

Answer

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.

Comments