如何在角度2中调用http调用?

时间:2016-02-11 05:40:11

标签: typescript angular

请告诉我如何在角度2中调用http调用并使用ng-repeat显示数据?

这是我的代码 http://plnkr.co/edit/u6LXrvGuC6f3bOT1tsaZ?p=preview

import {Component,View} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Router} from 'angular2/router';

@Component({

    templateUrl: 'home/home.html'
})


export class AppComponent {
   toDoModel;
  constructor(private _router:Router) {
   http.get('data.json')
      .map(res => res.json())

  }

  onclck(inputValue){
    alert(inputValue)
    this._router.navigate(['Second']);
  }

}

2 个答案:

答案 0 :(得分:3)

首先,您需要将Http实例注入到组件中:

export class AppComponent {
  toDoModel;

  constructor(private _router:Router,private http:Http) {
    this.http.get('data.json')
        .map(res => res.json())
  }
}

有两种方法可以在ngFor中显示您的数据:

  • 订阅get方法返回的observable

    @Component({
      template: `
        <ul>
          <li *ngFor="#elt of elements">{{elt.name}}</li>
        </ul>
      `
    })
    export class AppComponent {
      toDoModel;
    
      constructor(private _router:Router,private http:Http) {
        this.http.get('data.json')
            .map(res => res.json())
            .subscribe(data => {
              this.elements = data;
            });
      }
    }
    
  • 利用async管道

    @Component({
      template: `
        <ul>
          <li *ngFor="#elt of elements | async">{{elt.name}}</li>
        </ul>
      `
    })
    export class AppComponent {
      toDoModel;
    
      constructor(private _router:Router,private http:Http) {
        this.elements = this.http.get('data.json')
            .map(res => res.json());
      }
    }
    

在引导您的应用程序时,不要忘记指定HTTP_PROVIDERS

import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component';

bootstrap(AppComponent, [ HTTP_PROVIDERS ]);

这是相应的plunkr:https://plnkr.co/edit/bdFeiiAqrPDtFUdguw7s?p=preview

您还可以将HTTP处理放入专用服务中,如下所述:

答案 1 :(得分:0)

你需要它“注入”Http才能使用它

constructor(private http: Http){
  http.get('https://...')
    .map(response  => { response.json(); })
    .subscribe(value => { this.data = value;})  
}