Angular2 http.get 代码不工作

Angular2 http.get code not working

我正在 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;
            });
    }

}

出于某种原因,它正在获取数据但未显示。

我在这里错过了什么?

一切正常,只需更改为:

{{data?.title}}

在您的请求完成之前,

data 是未定义的。 elvis 运算符有助于避免空指针。

同时添加缺少的导入:

import 'rxjs/Rx';

我的代码在 "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;
            });

    }

}