0

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?

2
  • does your loading property get updated properly? Commented Apr 20, 2016 at 20:36
  • It just says Loading... and the response is null Commented Apr 20, 2016 at 20:38

2 Answers 2

5

My code works fine on "angular2": "2.0.0-beta.15" :

import {Component} from 'angular2/core';
import {HTTP_PROVIDERS,Http,Response} from 'angular2/http';
// see issue more detail here : https://github.com/angular/angular/issues/5632#issuecomment-167026172
import 'rxjs/Rx';



@Component({
    selector: 'my-app',
    template: `
      <h2>Basic Requests</h2>
      <button type="button" (click)="makeRequest()">Make Request</button>
      <div *ngIf="loading">loading......</div>
      <pre>title : {{array.title}}</pre>

    `,
    providers: [HTTP_PROVIDERS]
}
export class AppComponent {

    array = Array<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.array = res;
                this.loading = false;
            });

    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

It works. How can i catch http request error ? like request error code too.
You can do a .catch(err => console.log("here is my error", err)) after the subscribe.
1

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';

1 Comment

Getting response null ...no data coming in

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.