您现在的位置是:群英 > 开发技术 > web开发
HttpClientModule模块用于做什么,常见操作有哪些
Admin发表于 2022-06-22 17:46:53599 次浏览
这篇文章给大家分享的是“HttpClientModule模块用于做什么,常见操作有哪些”,文中的讲解内容简单清晰,对大家学习和理解有一定的参考价值和帮助,有这方面学习需要的朋友,接下来就跟随小编一起学习一下“HttpClientModule模块用于做什么,常见操作有哪些”吧。

该模块用于发送 Http 请求,用于发送请求的方法都返回 Observable 对象。

1、快速开始

1)、引入 HttpClientModule 模块

// app.module.ts
import { httpClientModule } from '@angular/common/http';
imports: [
  httpClientModule
]

2)、注入 HttpClient 服务实例对象,用于发送请求

// app.component.ts
import { HttpClient } from '@angular/common/http';

export class AppComponent {
	constructor(private http: HttpClient) {}
}

3)、发送请求

import { HttpClient } from "@angular/common/http"

export class AppComponent implements OnInit {
  constructor(private http: HttpClient) {}
  ngOnInit() {
    this.getUsers().subscribe(console.log)
  }
  getUsers() {
    return this.http.get("https://jsonplaceholder.typicode.com/users")
  }
}

2、请求方法

this.http.get(url [, options]);
this.http.post(url, data [, options]);
this.http.delete(url [, options]);
this.http.put(url, data [, options]);
this.http.get<Post[]>('/getAllPosts')
  .subscribe(response => console.log(response))

3、请求参数

1、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): HttpParams;
    set(param: string, value: string): HttpParams;
    delete(param: string, value?: string): HttpParams;
    toString(): string;
}

2、HttpParamsOptions 接口

declare interface HttpParamsOptions {
    fromString?: string;
    fromObject?: {
        [param: string]: string | ReadonlyArray<string>;
    };
    encoder?: HttpParameterCodec;
}

3、使用示例

import { HttpParams } from '@angular/common/http';

let params = new HttpParams({ fromObject: {name: "zhangsan", age: "20"}})
params = params.append("sex", "male")
let params = new HttpParams({ fromString: "name=zhangsan&age=20"})

4、请求头

请求头字段的创建需要使用 HttpHeaders 类,在类实例对象下面有各种操作请求头的方法。

export declare class HttpHeaders {
    constructor(headers?: string | {
        [name: string]: string | string[];
    });
    has(name: string): boolean;
    get(name: string): string | null;
    keys(): string[];
    getAll(name: string): string[] | null;
    append(name: string, value: string | string[]): HttpHeaders;
    set(name: string, value: string | string[]): HttpHeaders;
    delete(name: string, value?: string | string[]): HttpHeaders;
}
let headers = new HttpHeaders({ test: "Hello" })

5、响应内容

declare type HttpObserve = 'body' | 'response';
// response 读取完整响应体
// body 读取服务器端返回的数据
this.http.get(
  "https://jsonplaceholder.typicode.com/users", 
  { observe: "body" }
).subscribe(console.log)

6、拦截器

拦截器是 Angular 应用中全局捕获和修改 HTTP 请求和响应的方式。(Token、Error)

拦截器将只拦截使用 HttpClientModule 模块发出的请求。

ng g interceptor <name>


6.1 请求拦截

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor() {}
	// 拦截方法
  intercept(
  	// unknown 指定请求体 (body) 的类型
    request: HttpRequest<unknown>,
    next: HttpHandler
     // unknown 指定响应内容 (body) 的类型
  ): Observable<HttpEvent<unknown>> {
    // 克隆并修改请求头
    const req = request.clone({
      setHeaders: {
        Authorization: "Bearer xxxxxxx"
      }
    })
    // 通过回调函数将修改后的请求头回传给应用
    return next.handle(req)
  }
}

6.2 响应拦截

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor() {}
	// 拦截方法
  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<any> {
    return next.handle(request).pipe(
      retry(2),
      catchError((error: HttpErrorResponse) => throwError(error))
    )
  }
}

6.3 拦截器注入

import { AuthInterceptor } from "./auth.interceptor"
import { HTTP_INTERCEPTORS } from "@angular/common/http"

@NgModule({
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ]
})

7、Angular Proxy

1、在项目的根目录下创建 proxy.conf.json 文件并加入如下代码

{
 	"/api/*": {
    "target": "http://localhost:3070",
    "secure": false,
    "changeOrigin": true
  }
}
  • /api/*:在应用中发出的以 /api 开头的请求走此代理

  • target:服务器端 URL

  • secure:如果服务器端 URL 的协议是 https,此项需要为 true

  • changeOrigin:如果服务器端不是 localhost, 此项需要为 true

2、指定 proxy 配置文件 (方式一)

"scripts": {
  "start": "ng serve --proxy-config proxy.conf.json",
}

3、指定 proxy 配置文件 (方式二)

"serve": {
  "options": {
    "proxyConfig": "proxy.conf.json"
  },

该模块用于发送 Http 请求,用于发送请求的方法都返回 Observable 对象。


关于“HttpClientModule模块用于做什么,常见操作有哪些”的内容就介绍到这,感谢各位的阅读,相信大家对HttpClientModule模块用于做什么,常见操作有哪些已经有了进一步的了解。大家如果还想学习更多知识,欢迎关注群英网络,小编将为大家输出更多高质量的实用文章!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

相关信息推荐
2022-11-19 17:50:33 
摘要:setup函数是一个新的组件选项。作为在组件内使用Composition API的入口点。本篇文章就给大家介绍下setup函数,希望对大家有所帮助!
2022-06-16 17:06:13 
摘要:golang处理输入的方法:1、【fmt.Scan】交互式接受输入,通过空格来分词;2、【fmt.Scanln】要指定接收输入的变量名和变量数;3、【 fmt.Scanf】需要指定输入的格式,直接把不需要的部分过滤掉。
2022-09-15 17:48:27 
摘要:本篇文章给大家带来了关于Java的相关知识,其中主要整理了实现多线程的四种方式相关问题,包括了继承Thread类、实现Callable接口通过FutureTask包装器来创建Thread线程、使用ExecutorService、Callable、Future实现有返回结果的多线程等等内容,下面一起来看一下,希望对大家有帮助。
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部