Satch3000 Satch3000 - 7 months ago 31
Javascript Question

Angular2 http.get code not working

I am trying out this code in Angular2 beta 15.

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.title}}</pre>

`

})
export class AppComponent {

data: any;
loading: boolean;

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

}


For some reason it's getting the data but not displaying it.

What I'm I missing here?

Answer

Everything looks ok, just change to:

{{data?.title}}

data is undefined until your request completes. elvis operator helps to avoid null pointer.

Also add missing import:

import 'rxjs/Rx';