Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use HttpClientModule Module in Angular

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use the HttpClientModule module in Angular. It is very detailed and has certain reference value. Friends who are interested must finish it!

This module is used to send a Http request, and the methods used to send the request return an Observable object.

1. Quick start

Introduction of HttpClientModule module

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

Inject HttpClient service instance objects to send requests

/ / app.component.tsimport {HttpClient} from'@ angular/common/http';export class AppComponent {constructor (private http: HttpClient) {}}

Send a request

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")}})

two。 Request method

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 ('/ getAllPosts') .subscribe (response = > console.log (response))

3. Request parameter

HttpParams class

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 interface

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

Use the example

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. Request header

The request header field needs to be created using the HttpHeaders class, and there are various methods to manipulate the request header under the class instance object.

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. Response content

Declare type HttpObserve = 'body' |' response';// response reads the complete response body / / body reads the data returned by the server this.http.get ("https://jsonplaceholder.typicode.com/users", {observe:" body "}) .subscribe (console.log)

6. Interceptor

Interceptor is a way to globally capture and modify HTTP requests and responses in Angular applications. (Token, Error)

The interceptor will only intercept requests made using the HttpClientModule module.

$ng g interceptor

6.1 request interception

@ Injectable () export class AuthInterceptor implements HttpInterceptor {constructor () {} / / intercept method intercept (/ / unknown specifies the type of the request body (body) request: HttpRequest Next: HttpHandler / / unknown specifies the type of body): Observable {/ / Clone and modify the request header const req = request.clone ({setHeaders: {Authorization: "Bearer xxxxxxx"}}) / / pass the modified request header back to the application return next.handle (req)} through the callback function

6.2 response intercept

@ Injectable () export class AuthInterceptor implements HttpInterceptor {constructor () {} / / interception method intercept (request: HttpRequest, next: HttpHandler): Observable {return next.handle (request) .pipe (retry (2), catchError ((error: HttpErrorResponse) = > throwError (error)}}

6.3 interceptor injection

Import {AuthInterceptor} from ". / auth.interceptor" import {HTTP_INTERCEPTORS} from "@ angular/common/http" @ NgModule ({providers: [{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}]})

7. Angular Proxy

Create the proxy.conf.json file in the root directory of the project and add the following code

{"/ api/*": {"target": "http://localhost:3070"," secure ": false," changeOrigin ": true}}

Requests made by / api/: in the application that begin with / api go through this proxy

Target: server-side URL

Secure: if the protocol of server-side URL is https, this item needs to be true

ChangeOrigin: if the server is not localhost, this item needs to be true

Specify proxy profile (Formula 1)

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

Specify proxy profile (formula II)

/ / "serve" in the angular.json file: {"options": {"proxyConfig": "proxy.conf.json"}, these are all the contents of the article "how to use the HttpClientModule module in Angular". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report