angular 4 http 之web api 服务
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了angular 4 http 之web api 服务,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4714字,纯文字阅读大概需要7分钟。
内容图文
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 快多了
原文:http://www.cnblogs.com/sulishibaobei/p/7371800.html
内容总结
以上是互联网集市为您收集整理的angular 4 http 之web api 服务全部内容,希望文章能够帮你解决angular 4 http 之web api 服务所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。