這個組件全部放在一個文件夾中,先講下編寫組件的思路吧,其中也遇到不少坑
- 既然是編寫組件當(dāng)時首先是創(chuàng)建一個單獨(dú)的子文件夾阅酪,先寫一個類似hello world的簡單例子舵揭,在頁面跑起來,再一步步添加?xùn)|西;
</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是在初始化時獲取相關(guān)數(shù)據(jù)憔足,這里是用HeroService的方法獲取模板渲染的數(shù)據(jù)
this._http.getHeroes().then(data => this.heroes = data);
}
public heroes: Hero[];
//定義添加newHero方法,加入heroes數(shù)組中
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定義服務(wù)屬性酒繁,使用Rxjs發(fā)送異步請求獲取數(shù)據(jù)
<pre>
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Hero} from './hero'; //導(dǎo)入數(shù)據(jù)結(jié)構(gòu)
import 'rxjs/Rx'; //導(dǎo)入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定義數(shù)據(jù)結(jié)構(gòu)接口
<pre>
export interface Hero {
name: string;
id: number;
}
</pre>
5.herodata.json<Hero[]>類型的數(shù)組數(shù)據(jù)
<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>