anguar2-http实例
这个组件全部放在一个文件夹中,先讲下编写组件的思路吧,其中也遇到不少坑
- 既然是编写组件当时首先是创建一个单独的子文件夹,先写一个类似hello world的简单例子,在页面跑起来,再一步步添加东西;
</br>
-
http.component.ts主文件,在HttpComponent组件模板中引入HeroList子组件。
<pre>
import {Component} from 'angular2/core';
import {HeroList} from './hero-list.component';
import {Hero} from './hero';
@Component({
selector: 'http-component',
template:<h1>Tour of Heroes !</h1> <hero-list></hero-list>
,
directives: [HeroList], //此处必须注入依赖的子组件
providers: [HTTP_PROVIDERS] // 也可在bootstrap中添加,与ROUTER_PROVIDERS一样
})
export class HttpComponent {}
</pre> -
hero-list.ts文件,定义HeroList组件模板
<pre>
import {Component,OnInit,Injectable} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
import {HeroService} from './hero.service';
import {Hero} from './hero';
@Component({
selector: 'hero-list',
template:<h3>Heroes:</h3> <ul> <li *ngFor="#hero of heroes">{{hero.name}}</li> </ul> New Hero: <input #newHero/> <button (click)="addHero(newHero)">Add Hero</button>
,
providers: [
HTTP_PROVIDERS,
HeroService // 依赖的文件必须提供
]
})
export class HeroList implements OnInit{
constructor(private _http: HeroService) {}
ngOnInit() { //OnInit是在初始化时获取相关数据,这里是用HeroService的方法获取模板渲染的数据
this._http.getHeroes().then(data => this.heroes = data);
}
public heroes: Hero[];
//定义添加newHero方法,加入heroes数组中
addHero(hero) {
if(!hero.value) return;
let newHero: Hero = {
name: hero.value,
id: this.heroes.length
}
this.heroes.push(newHero);
hero.value = "";
}
}
</pre>
3.hero-sevice.ts定义服务属性,使用Rxjs发送异步请求获取数据
<pre>
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Hero} from './hero'; //导入数据结构
import 'rxjs/Rx'; //导入rx模块提供一步请求用
@Injectable()
export class HeroService {
constructor(private http: Http) {}
public heroes: Hero[];
private _heroUrl = "app/http-client/heroes.json";
getHeroes() {
return this.http.get(this._heroUrl)
.toPromise()
.then(res => <Hero[]>res.json());
}
}
</pre>
4.hero.ts定义数据结构接口
<pre>
export interface Hero {
name: string;
id: number;
}
</pre>
5.herodata.json<Hero[]>类型的数组数据
<pre>
[{"name": "SpiderMan", "id": 1},
{"name": "Kongfu Pander", "id": 2},
{"name": "Icon Man", "id": 3},
{"name": "Gorilla", "id": 4}]
</pre>
.注:页头要引入http.dev.js否则报错
<pre>
<script src="node_modules/angular2/bundles/http.dev.js"></script>
</pre>