ng2 http
http API
- 请求防抖
- 监听进度事件
- 获取完整的请求,而不仅仅是json数据
- jsonp
- 请求非json数据
- 错误处理
- 重试
- 添加HTTP header头
- post请求 默认使用
json
发送,如果要使用application/x-www-form-urlencoded
需要把body转化为require('querystring').stringify(body)
- 拦截器
- 记录日志
- 缓存
HTTP 请求是可以通过 unsubscribe() 方法来取消的。
在app.module中导入HttpClientModule
import { HttpClientModule } from "@angular/common/http";
imports: [ HttpClientModule ],
组件中注入
import { HttpClient } from "@angular/common/http";
constructor(private http: HttpClient) {}
get post
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { stringify } from 'querystring';
postData() {
const headers = new HttpHeaders()
.append('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
const body = stringify({ name: "post-json" });
this.http.post('http://localhost:3000/post', body , {
params: { test: 'pppppp' }, // query
headers: headers, // 头信息
responseType: 'json', // 后台返回的数据类型
}).subscribe(res => {
console.log(res);
})
}
http请求拦截器
noop-interceptor.ts
import { Injectable } from "@angular/core";
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
} from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
let secureReq;
if (req.method === "GET") {
const newParams = req.params.set("token", "233");
secureReq = req.clone({params: newParams});
}
if (req.method === "POST") {
const newBody = { ...req.body, token: "233" };
secureReq = req.clone({body: newBody});
}
// 请求发出前
return next.handle(secureReq).pipe(
tap(r => {
// 请求响应时
console.log(r);
}),
);
}
}