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 快多了