import { HttpModule } from '@angular/http'; @NgModule({ imports: [BrowserModule, FormsModule, HttpModule], declarations: [AppComponent, UserComponent], bootstrap: [AppComponent] }) export class AppModule { }
import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; // (1) import 'rxjs/add/operator/map'; // (2) interface Member { id: string; login: string; avatar_url: string; } @Component({ selector: 'sl-members', template: ` <h3>Angular Orgs Members</h3> <ul *ngIf="members"> <li *ngFor="let member of members;"> <p> <img [src]="member.avatar_url" width="48" height="48"/> ID:<span>{{member.id}}</span> Name: <span>{{member.login}}</span> </p> </li> </ul> ` }) export class MembersComponent implements OnInit { members: Member[]; constructor(private http: Http) { } // (3)使用 DI 方式注入 http 服務 ngOnInit() { this.http.get(`https://api.github.com/orgs/angular/members?page=1&per_page=5`) // (4)調用 http 服務的 方法,設置請求地址併發送 HTTP 請求 .map(res => res.json()) // (5)調用 Response 對象的 方法,把響應體轉成 JSON 對象 .subscribe(data => { if (data) this.members = data; // (6)把請求的結果,賦值給對應的屬性 }); } }get()json()
import { MembersComponent } from './members.component'; @NgModule({ imports: [BrowserModule, FormsModule, HttpModule], declarations: [AppComponent, UserComponent, MembersComponent], bootstrap: [AppComponent] }) export class AppModule { }
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <sl-members></sl-members> `, }) export class AppComponent {}