导入 Http 模块

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="" height=""/>
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 服务的 get() 方法,设置请求地址并发送 HTTP 请求
.map(res => res.json()) // (5)调用 Response 对象的 json() 方法,把响应体转成 JSON 对象
.subscribe(data => {
if (data) this.members = data; // (6)把请求的结果,赋值给对应的属性
});
}
}

声明 MembersComponent 组件

import { MembersComponent } from './members.component';

@NgModule({
imports: [BrowserModule, FormsModule, HttpModule],
declarations: [AppComponent, UserComponent, MembersComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

使用 MembersComponent 组件

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template: `
<sl-members></sl-members>
`,
})
export class AppComponent {}
05-11 15:05