Angular2 http.get代码无效

时间:2016-04-20 19:59:53

标签: javascript angularjs angular

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

}

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

我在这里失踪了什么?

2 个答案:

答案 0 :(得分:5)

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

    }

}

答案 1 :(得分:1)

一切看起来都不错,只需改为:

{{data?.title}}

在您的请求完成之前,

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

还添加缺少的导入:

import 'rxjs/Rx';