angular HttpClientModule

angular HttpClientModule,第1张

文章目录 说明常用方法传参示例设置请求头设置响应体拦截器

说明

就是对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
  }],

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/926078.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存