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 ...
随机推荐
- kotlin 记录(已弃坑)
kotlin 有些是转载内容 使用nullable值以及空值检测 引用或函数返回值如果可能为null值,则必须显式标记nullable. (在类型后面跟一个问号表示这个对象可能为空,跟两个感叹号表示这 ...
- Educational Codeforces Round 54 (Rated for Div. 2) DE
D 给出一个无向图,需要删去一些边,想知道最后能有多少个点到1的距离还是过去那么短 如果求一个最短路,然后从删边的角度看,看起来很难做,但是如果从零开始加边就会有做法,如同prim那样,先加入和1直接 ...
- mysql 的行转列 PIVOT 的使用
语句:SELECT DataDate , PropertyText , DataValue FROM RPT_ReportProperty p WITH ( NOLOCK ) JOIN RPT_Rep ...
- Kaggle 项目之 Digit Recognizer
train.csv 和 test.csv 包含 1~9 的手写数字的灰度图片.每幅图片都是 28 个像素的高度和宽度,共 28*28=784 个像素点,每个像素值都在 0~255 之间. train. ...
- codeforces GYM 100971F 公式题或者三分
F. Two Points time limit per test 2 seconds memory limit per test 256 megabytes input standard input ...
- [Eclipse]保存java文件时,自动删除不需要的包import
1.修改设定:Window->Preferences 2.效果: =>
- ADC和RTC的寄存器的读取
ADC的寄存器读取,int adc_read(void){ int result; #if ADSTART==0 result = ADC.ADCDAT0&0x3ff; while(!(ADC ...
- ajax实现用户注册
需求分析 页面中给出注册表单: 在username input标签中绑定onblur事件处理函数. 当input标签失去焦点后获取 username表单字段的值,向服务端发送AJAX请求: djang ...
- 如何成为 Python 高手
这篇文章主要是对我收集的一些文章的摘要.因为已经有很多比我有才华的人写出了大量关于如何成为优秀Python程序员的好文章. 我的总结主要集中在四个基本题目上:函数式编程,性能,测试,编码规范.如果一个 ...
- 引发事件代码封装成OnEventName
引发事件的代码,通常可以封装成“On+事件名称”的方法(On:表示当“什么什么”的时候),如下所示: 1:引发事件代码: if (PropertyChanged != null)//为了实现将数据源的 ...