angular 4 http 之web api 服务

Angular Http是获取和保存数据的。主要是为了取到我json文件里的数据。

直接上代码吧:

1.  先介绍Promise模式的:(直接代码)

 heroes.json:

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:

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写什么呢?

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.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);
}

 引入的包是这几个:

1
import 'rxjs/add/operator/toPromise';

 Observable模式是这样算的:

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 快多了
posted @ 2017-08-16 10:01  前端进阶中  阅读(539)  评论(0编辑  收藏  举报