anguar2-http实例

这个组件全部放在一个文件夹中,先讲下编写组件的思路吧,其中也遇到不少坑

  • 既然是编写组件当时首先是创建一个单独的子文件夹,先写一个类似hello world的简单例子,在页面跑起来,再一步步添加东西;

  1. http.component.ts主文件,在HttpComponent组件模板中引入HeroList子组件。


    import {Component} from 'angular2/core';
    import {HeroList} from './hero-list.component';
    import {Hero} from './hero';
    @Component({
    selector: 'http-component',
    template:

    Tour of Heroes !

    ,
    directives: [HeroList], //此处必须注入依赖的子组件
    providers: [HTTP_PROVIDERS] // 也可在bootstrap中添加,与ROUTER_PROVIDERS一样
    })
    export class HttpComponent {}

  2. hero-list.ts文件,定义HeroList组件模板


    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:

    Heroes:

    • {{hero.name}}
    New Hero:
    ,
    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 = "";
}
}

3.hero-sevice.ts定义服务属性,使用Rxjs发送异步请求获取数据


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 => res.json());
}
}

4.hero.ts定义数据结构接口

export interface Hero {
name: string;
id: number;
}

5.herodata.json类型的数组数据

[{"name": "SpiderMan", "id": 1},
{"name": "Kongfu Pander", "id": 2},
{"name": "Icon Man", "id": 3},
{"name": "Gorilla", "id": 4}]

.注:页头要引入http.dev.js否则报错


你可能感兴趣的:(anguar2-http实例)