就是对ajax的类似封装
常用方法this.http.get(url,[,options])
this.http.post(url,data,[,options])
this.http.delete(url,[,options])
this.http.put(url,,data,[,options])
传参
通过HttpParams传参
export declare class HttpParams{
constructor(options?:HttpParamsOptions);
has(param:string):boolean;
get(param:string):string|null;
getAll(param:string):string|null;
keys():string[];
append(param:string,value:string):HttpParam;
set(param:string,value:string):HttpParam;
delete(param:string,value:string):HttpParam;
toString():string;
}
HttpParamsOptions
declare interface HttpParamsOptions{
fromString?:string;
fromObject?:{
[param:string]string|ReadonlyArray<string>
};
encoder?:HttpParamterCode
}
示例
var url1 = "https://api.seniverse.com/v3/weather/daily.json?key=SCYrvkytJze9qyzOh1&location=beijing&language=zh-Hans&unit=c"
var url2 = "https://api.seniverse.com/v3/weather/daily.json"
var obj = {
key: "SCYrvkytJze9qyzOh1",
location: 'beijing',
language: 'zh-Hans',
unit:'c'
}
this.http.post(url2, {
params: obj
}).subscribe(data => {
debugger
console.log(data)
})
上面的是简写,也可以用HttpParams
设置请求头let headers = new HttpHeaders({
test:"hello world"
});
this.http.get(url,{headers}).subscribe()
设置响应体
this.http.get(url,{observe:'body'|'response'})
拦截器
全局捕获请求和响应,只能捕捉httpClientModule,用AJAX就捕捉不到
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { catchError, Observable, retry, throwError } from 'rxjs';
@Injectable()
export class CommonAjaxInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
debugger;
//写一些业务逻辑,包括token的处理啊什么的
let req = request.clone({
setHeaders: {
token:"token"
}
})
return next.handle(req).pipe(retry(3),catchError(err=>throwError(err)))
}
}
在appModule中需要注入
providers: [TestService, {
provide: HTTP_INTERCEPTORS,
useClass: CommonAjaxInterceptor,
multi:true
}],
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)