AngularX Http服务总结
自己经常用的方式:
1.首先看httpModule
Angular2的http访问经常采用两种方式:
共同点:导入相应的Module
import {Http, RequestOptions, Response} from '@angular/http';
在module文件中配置
import {HttpModule} from '@angular/http';
imports: [ // import Angular's modules
BrowserModule,
BrowserAnimationsModule,
HttpModule,
在service的构造器中进行注入
constructor(private http: Http) {
super();
}
1.1 用promise实现服务层返回
// 获取设置
public getOptions(): Promise<any> {
return this.http
.get(this._optionApiUrl)
.toPromise()
.then((res: Response) => res.json())
.catch((error: any) => Observable.throw(error || 'Server error'));
}
其中then里面、catch里面可以自己自定义,之后控制层调用服务层
/*获取经营单位数据*/
public getUnitInfo() {
this.parkManageService.getUnitInfo().then(data => {
this.units = data.unit;
});
}
1.2 用Observable实现服务层
/*根据查询条件获取数据*/
public getParkInfoByParams(jsonObject: any): Observable<any> {
return this.http.request(this.getParkInfoByParamUrl, new RequestOptions({ method: 'GET', body: jsonObject }))
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error || 'Server error'));
}
控制层调用
/*请求后台数据*/
public getSuggests(pageNum: number) {
this.suggestService.getSuggestInfo(`/Bi/${ConstantValue.CHECKCODE}/querySuggest/${pageNum}/${this.pageSize}`,
this.getSearchParams())
.subscribe(
data => {
// console.log(data);
...............
},
error => console.log('errorMsg:请求建议信息失败...')
);
}
2.Angular4 推出了一个新的http请求module:HttpClientModule
导入新的 HTTP Module
import {HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
需要注意的是,现在 JSON 是默认的数据格式,我们不需要再进行显式的解析。即我们不需要再使用以下代码:
http.get(url).map(res => res.json()).subscribe(...)
现在我们可以这样写:
http.get(url).subscribe(...)
发送get请求
public saveUser2() {
let url = "http://localhost:8080/financial/user/getUsers/2";
this.httpClient
.get(url)
.subscribe(data => {
console.log(data)
});
}
带参数请求(REST方式请求不建议这样使用参数)
import {HttpParams} from "@angular/common/http";
const params = new HttpParams()
.set('orderBy', '"$key"')
.set('limitToFirst', "1");
this.courses$ = this.http
.get("/courses.json", {params}) .subscribe(data => _.values(data))
需要注意的是,我们通过链式语法调用 set() 方法,构建 HttpParams 对象。这是因为 HttpParams 对象是不可变的,通过 set() 方法可以防止该对象被修改。
每当调用 set() 方法,将会返回包含新值的 HttpParams 对象,因此如果使用下面的方式,将不能正确的设置参数。
const params = new HttpParams();
params.set('orderBy', '"$key"')
params.set('limitToFirst', "1");
使用 fromString 语法
const params = new HttpParams({fromString: 'orderBy="$key"&limitToFirst=1'});
使用 request() API
const params = new HttpParams({fromString: 'orderBy="$key"&limitToFirst=1'});
this.courses$ = this.http
.request(
"GET",
"/courses.json",
{
responseType:"json",
params
})
.subscribe(data => _.values(data));
设置 HTTP Headers
const headers = new HttpHeaders().set("X-CustomHeader", "custom header value");
this.courses$ = this.http
.get(
"/courses.json",
{headers})
.subscribe(data => _.values(data));
发送 Put 请求
const headers = new HttpHeaders().set("Content-Type", "application/json");
this.http.put("/courses/-KgVwECOnlc-LHb_B0cQ.json",
{
"courseListIcon": ".../main-page-logo-small-hat.png",
"description": "Angular Tutorial For Beginners TEST",
"iconUrl": ".../angular2-for-beginners.jpg",
"longDescription": "...",
"url": "new-value-for-url"
},
{headers})
.subscribe(
val => {
console.log("PUT call successful value returned in body", val);
},
response => {
console.log("PUT call in error", response);
},
() => {
console.log("The PUT observable is now completed.");
}
);
}
发送 Patch 请求
httpPatchExample() {
this.http.patch("/courses/-KgVwECOnlc-LHb_B0cQ.json",
{
"description": "Angular Tutorial For Beginners PATCH TEST",
})
.subscribe(
(val) => {
console.log("PATCH call successful value returned in body",
val);
},
response => {
console.log("PATCH call in error", response);
},
() => {
console.log("The PATCH observable is now completed.");
});
}
发送 Delete 请求
httpDeleteExample() {
this.http.delete("/courses/-KgVwECOnlc-LHb_B0cQ.json")
.subscribe(
(val) => {
console.log("DELETE call successful value returned in body", val);
},
response => {
console.log("DELETE call in error", response);
},
() => {
console.log("The DELETE observable is now completed.");
});
}
发送 Post 请求
httpPostExample() {
this.http.post("/courses/-KgVwECOnlc-LHb_B0cQ.json",
{
"courseListIcon": "...",
"description": "TEST",
"iconUrl": "..",
"longDescription": "...",
"url": "new-url"
})
.subscribe(
(val) => {
console.log("POST call successful value returned in body", val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
}
避免重复请求
duplicateRequestsExample() {
const httpGet$ = this.http
.get("/courses.json")
.map(data => _.values(data));
httpGet$.subscribe(
(val) => console.log("logging GET value", val)
);
this.courses$ = httpGet$;
}
在上面例子中,我们正在创建了一个 HTTP observable 对象 httpGet$,接着我们直接订阅该对象。然后,我们把 httpGet$ 对象赋值给 courses$ 成员变量,最后在模板中使用 async 管道订阅该对象。这将导致发送两个 HTTP 请求,在这种情况下,请求显然是重复的,因为我们只希望从后端查询一次数据。为了避免发送冗余的请求,我们可以使用 RxJS 提供的 shareReplay 操作符:
// put this next to the other RxJs operator imports
import 'rxjs/add/operator/shareReplay'; const httpGet$ = this.http
.get("/courses.json")
.map(data => _.values(data))
.shareReplay();
并行发送多个请求
并行发送 HTTP 请求的一种方法是使用 RxJs 中的 forkjoin 操作符:
import 'rxjs/add/observable/forkJoin';
parallelRequests() {
const parallel$ = Observable.forkJoin(
this.http.get('/courses/-KgVwEBq5wbFnjj7O8Fp.json'),
this.http.get('/courses/-KgVwECOnlc-LHb_B0cQ.json')
);
parallel$.subscribe(
values => {
console.log("all values", values)
}
);
}
顺序发送 Http 请求
sequentialRequests() {
const sequence$ = this.http.get<Course>('/courses/-KgVwEBq5wbFnjj7O8Fp.json')
.switchMap(course => {
course.description+= ' - TEST ';
return this.http.put('/courses/-KgVwEBq5wbFnjj7O8Fp.json', course)
});
sequence$.subscribe();
}
获取顺序发送 Http 请求的结果
sequentialRequests() {
const sequence$ = this.http.get<Course>('/courses/-KgVwEBq5wbFnjj7O8Fp.json')
.switchMap(course => {
course.description+= ' - TEST ';
return this.http.put('/courses/-KgVwEBq5wbFnjj7O8Fp.json', course)
},
(firstHTTPResult, secondHTTPResult) => [firstHTTPResult, secondHTTPResult]);
sequence$.subscribe(values => console.log("result observable ", values) );
}
请求异常处理
throwError() {
this.http
.get("/api/simulate-error")
.catch( error => {
// here we can show an error message to the user,
// for example via a service
console.error("error catched", error);
return Observable.of({description: "Error Value Emitted"});
})
.subscribe(
val => console.log('Value emitted successfully', val),
error => {
console.error("This line is never called ",error);
},
() => console.log("HTTP Observable completed...")
);
}
当发生异常时,控制台的输出结果:
Error catched
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/simulate-error", ok: false, … }
Value emitted successfully {description: "Error Value Emitted"}
HTTP Observable completed...
Http 拦截器
定义拦截器
import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor} from "@angular/common/http";
import {HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const clonedRequest = req.clone({
headers: req.headers.set('X-CustomAuthHeader', authService.getToken())
});
console.log("new headers", clonedRequest.headers.keys());
return next.handle(clonedRequest);
}
}
配置拦截器
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
[ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ]
],
bootstrap: [AppComponent]
})
export class AppModule { }
Http 进度事件
longRequest() {
const request = new HttpRequest(
"POST", "/api/test-request", {},
{reportProgress: true});
this.http.request(request)
.subscribe(
event => {
if (event.type === HttpEventType.DownloadProgress) {
console.log("Download progress event", event);
}
if (event.type === HttpEventType.UploadProgress) {
console.log("Upload progress event", event);
}
if (event.type === HttpEventType.Response) {
console.log("response received...", event.body);
}
}
);
}
上面示例运行后,控制台的可能的输出结果:
Upload progress event Object {type: 1, loaded: 2, total: 2}
Download progress event Object {type: 3, loaded: 31, total: 31}
Response Received... Object {description: "POST Response"}
AngularX Http服务总结的更多相关文章
- solr服务中集成IKAnalyzer中文分词器、集成dataimportHandler插件
昨天已经在Tomcat容器中成功的部署了solr全文检索引擎系统的服务:今天来分享一下solr服务在海量数据的网站中是如何实现数据的检索. 在solr服务中集成IKAnalyzer中文分词器的步骤: ...
- Swift3.0服务端开发(一) 完整示例概述及Perfect环境搭建与配置(服务端+iOS端)
本篇博客算是一个开头,接下来会持续更新使用Swift3.0开发服务端相关的博客.当然,我们使用目前使用Swift开发服务端较为成熟的框架Perfect来实现.Perfect框架是加拿大一个创业团队开发 ...
- 启动了VSAN服务的主机不在vCenter集群中
背景: 这个问题的来源是,某用户将该ESXi主机直接夺取到另一个vCenterA的管辖中,而这个vCenterA中集群A开启了VSAN功能,导致再次反向夺取到vCenterB中的时候带有了来自于集群A ...
- node服务的监控预警系统架构
需求背景 目前node端的服务逐渐成熟,在不少公司内部也开始承担业务处理或者视图渲染工作.不同于个人开发的简单服务器,企业级的node服务要求更为苛刻: 高稳定性.高可靠性.鲁棒性以及直观的监控和报警 ...
- 通过AngularJS实现前端与后台的数据对接(二)——服务(service,$http)篇
什么是服务? 服务提供了一种能在应用的整个生命周期内保持数据的方法,它能够在控制器之间进行通信,并且能保证数据的一致性. 服务是一个单例对象,在每个应用中只会被实例化一次(被$injector实例化) ...
- 本人提供微软系.NET技术顾问服务,欢迎企业咨询!
背景: 1:目前微软系.NET技术高端人才缺少. 2:企业很难直接招到高端技术人才. 3:本人提供.NET技术顾问,保障你的产品或项目在正确的技术方向. 技术顾问服务 硬服务项: 1:提供技术.决策. ...
- 使用 Roslyn 编译器服务
.NET Core和 .NET 4.6中 的C# 6/7 中的编译器Roslyn 一个重要的特性就是"Compiler as a Service",简单的讲,就是就是将编译器开放为 ...
- C#高性能TCP服务的多种实现方式
哎~~ 想想大部分园友应该对 "高性能" 字样更感兴趣,为了吸引眼球所以标题中一定要突出,其实我更喜欢的标题是<猴赛雷,C#编写TCP服务的花样姿势!>. 本篇文章的主 ...
- 使用ServiceStack构建Web服务
提到构建WebService服务,大家肯定第一个想到的是使用WCF,因为简单快捷嘛.首先要说明的是,本人对WCF不太了解,但是想快速建立一个WebService,于是看到了MSDN上的这一篇文章 Bu ...
随机推荐
- SSH 登录时出现如下错误:Host key verification failed
注意:本文相关 Linux 配置及说明已在 CentOS 6.5 64 位操作系统中进行过测试.其它类型及版本操作系统配置可能有所差异,具体情况请参阅相应操作系统官方文档. 问题描述 使用 SS ...
- Spring boot 外部资源配置
tomcat配置访问图片路径映射到磁盘路径 首先,我在调试页面的时候发现,图片路径为: 1 /webapps/pic_son/img/1234565456.jpg 但是,tomcat中webapp ...
- angular中的cookies与cookieStore区别
设置cookie用put()方法: $cookies.put(key, value[, options]); $cookieStore.put(key, value); 例如设置一个cookie,名为 ...
- [Vue]组件——组件的data 必须是一个函数
普通的Vue实例data是一个对象: data: { count: 0 } 组件的data是一个方法: data: function () { return { count: 0 } } 详情见官网: ...
- 在 Ubuntu 里如何下载、安装和配置 Plank Dock
一个众所周知的事实就是,Linux 是一个用户可以高度自定义的系统,有很多选项可以选择 —— 作为操作系统,有各种各样的发行版,而对于单个发行版来说,又有很多桌面环境可以选择.与其他操作系统的用户一样 ...
- SQL , MERGE 简意
- Ubuntu下配置Nginx+PHP
1.安装Nginxapt-get install nginx 2.启动Nginxservice nginx start 3.访问服务器IP 如果看到“Welcome to nginx!”说明安装好了. ...
- Linux SSH隧道技术(端口转发,socket代理)
动态转发(SOCKS5代理): 命令格式:ssh -D <local port> <SSH Server> ssh -fnND 0.0.0.0:20058 172.16.50. ...
- nyoj299——如何优雅的写矩阵快速幂
Matrix Power Series 时间限制:1000 ms | 内存限制:65535 KB 难度:4 描述 Given a n × n matrix A and a positive i ...
- nyoj998——欧拉+折半查找
Sum 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 给你一个数N,使得在1~N之间能够找到x使得x满足gcd( x , N ) >= M, 求解gcd( ...