//配置已创建的服务:
import { MemberService } from "./member.service";
@NgModule({
// ...
providers: [MemberService]
})
export class AppModule { }
//导入已创建的服务
import { MemberService } from '../member.service';
//使用构造注入方式,注入服务
export class MembersComponent implements OnInit {
// ...
constructor(private memberService: MemberService) { }
}
创建 MemberService 服务
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class MemberService {
constructor(private http: Http) { }
getMembers() {
return this.http
.get(`https://api.github.com/orgs/angular/members?page=1&per_page=5`)
.map(res => res.json())
}
}
使用 MemberService 服务
import { MemberService } from "./member.service";
@Component({...})
export class MembersComponent implements OnInit {
members: Member[];
constructor(private memberService: MemberService) { }
ngOnInit() {
this.memberService.getMembers()
.subscribe(data => {
if (data) this.members = data;
});
}
}