首页 > web前端 > js教程 > 正文

浅析Angular中HttpClientModule模块有什么用?怎么用?

青灯夜游
发布: 2021-09-28 10:53:27
转载
2328人浏览过

本篇文章带大家了解一下angular中的httpclientmodule模块,介绍一下httpclientmodule模块的使用方法,希望对大家有所帮助!

浅析Angular中HttpClientModule模块有什么用?怎么用?

该模块用于发送 Http 请求,用于发送请求的方法都返回 Observable 对象。【相关教程推荐:《angular教程》】

1.  快速开始

引入 HttpClientModule 模块

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

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

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

export class AppComponent {
  constructor(private http: HttpClient) {}
}
登录后复制

发送请求

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.  请求参数

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;
}
登录后复制

HttpParamsOptions 接口

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

使用示例

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>
登录后复制

1.png

2.png

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

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

{
     "/api/*": {
        "target": "http://localhost:3070",
        "secure": false,
        "changeOrigin": true
      }
}
登录后复制
/api/:在应用中发出的以 /api 开头的请求走此代理target:服务器端 URLsecure:如果服务器端 URL 的协议是 https,此项需要为 truechangeOrigin:如果服务器端不是 localhost, 此项需要为 true

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

// package.json
"scripts": {
  "start": "ng serve --proxy-config proxy.conf.json",
}
登录后复制

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

// angular.json 文件中
"serve": {
  "options": {
    "proxyConfig": "proxy.conf.json"
  },
登录后复制

更多编程相关知识,请访问:编程入门!!

以上就是浅析Angular中HttpClientModule模块有什么用?怎么用?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:掘金社区网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号