Angular Http是获取和保存数据的。主要是为了取到我json文件里的数据。html
直接上代码吧:web
1. 先介绍Promise模式的:(直接代码)json
heroes.json: bootstrap
1
2
3
4
5
6
7
8
|
{
"data": [
{ "id": 1, "name": "Windstorm" },
{ "id": 2, "name": "Bombasto" },
{ "id": 3, "name": "Magneta" },
{ "id": 4, "name": "Tornado" }
]
}
|
http确定是要有服务的,下面先看service的代码: hero.service.promise.ts:api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
@Injectable()
export class HeroService {
//注意这里的路径,找的是app文件下的heroes.json文件
private heroesUrl = 'app/heroes.json';
constructor (private http: Http) {}
getHeroes (): Promise<
Hero
[]> {
console.log(this.heroesUrl);
return this.http.get(this.heroesUrl)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Promise.reject(errMsg);
}
}
|
主要是提供了一个getHeroes ()方法:
下面看hero.component.promise.ts里面怎么用呢:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service.promise';
@Component({
selector: 'hero-list-promise',
templateUrl: './hero-list.component.html',
providers: [ HeroService ],
styles: ['.error {color:red;}']
})
export class HeroListPromiseComponent implements OnInit {
errorMessage: string;
heroes: Hero[];
mode = 'Promise';
constructor (private heroService: HeroService) {}
ngOnInit() { this.getHeroes(); }
getHeroes() {
this.heroService.getHeroes()
.then(
heroes => this.heroes = heroes,
error => this.errorMessage = <
any
>error);
}
}
|
固然得定义一个hero.ts类:
1
2
3
4
5
|
export class Hero {
constructor(
public id: number,
public name: string) { }
}
|
接下来看一下咱们的hero.compoennt.html写什么呢?promise
1
2
3
4
5
|
<
h1
>Tour of Heroes ({{mode}})</
h1
>
<
h3
>Heroes:</
h3
>
<
ul
>
<
li
*ngFor="let hero of heroes">{{hero.name}}</
li
>
</
ul
>
|
就是这么简单。app
而后咱们在app.compoennt.ts里面引入咱们的标签:
1
|
<
hero-list-promise
></
hero-list-promise
>
|
如今最关键的就是在Module.ts中如何配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { HeroListComponent } from './toh/hero-list.component';
import { HeroListPromiseComponent } from './toh/hero-list.component.promise';
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
],
declarations: [
AppComponent,
HeroListPromiseComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
|
最简单和日常的配置,和往常同样。
2.第二种是web api形式。
有一个文件hero-data.ts(这里就不须要heroes.json文件了)
1
2
3
4
5
6
7
8
9
10
11
12
|
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class HeroData implements InMemoryDbService {
createDb() {
let heroes = [
{ id: 1, name: 'Windstorm' },
{ id: 2, name: 'Bombasto' },
{ id: 3, name: 'Magneta' },
{ id: 4, name: 'Tornado' }
];
return {heroes};
}
}
|
module.ts须要这样配置:加上:
1
2
3
4
5
|
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { HeroData } from './hero-data';
imports:[
InMemoryWebApiModule.forRoot(HeroData);
]
|
hero.service.promise.ts里面须要修改下路径就能够。这要修改服务便可,其余的代码勿改动。
1
|
private heroesUrl = 'api/heroes';
|
这里已经和heroes.json是没有任何关系了。api是指web api在module.ts里面配置的。angular-in-memory-web-api
heroes是hero-data.ts 里面return 回来的heroes。
这两种获得的结果实际上是同样的。
下面说说Observable模式的: 使用都是同样的。
只是服务里的这处代码不同:
promise模式:
1
2
3
4
5
6
7
|
getHeroes (): Promise<
Hero
[]> {
console.log(this.heroesUrl);
return this.http.get(this.heroesUrl)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
|
引入的包是这几个:ide
1
|
import 'rxjs/add/operator/toPromise';
|
而Observable模式是这样算的:this
1
2
3
4
5
|
getHeroes(): Observable<
Hero
[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
|
引入:
1
2
3
|
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
|
而后就同样了
实际证实直接取Json数据比用web api 快多了