This module is used to send Http requests, and the methods used to send requests all return An Observable.

1. Start fast

  1. Introduce the HttpClientModule module

    // app.module.ts
    import { httpClientModule } from '@angular/common/http';
    imports: [
      httpClientModule
    ]
    Copy the code
  2. Inject an HttpClient service instance object for sending requests

    // app.component.ts
    import { HttpClient } from '@angular/common/http';
    
    export class AppComponent {
      constructor(private http: HttpClient){}}Copy the code
  3. Send the 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")}}Copy the code

2. Request method

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

3. Request parameters

  1. 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;
    }
    Copy the code
  2. HttpParamsOptions interface

    declare interfaceHttpParamsOptions { fromString? :string; fromObject? : { [param:string] :string | ReadonlyArray<string>; }; encoder? : HttpParameterCodec; }Copy the code
  3. Use the sample

    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"})
    Copy the code

4. The request header

Request header fields are created using the HttpHeaders class, which has various methods for manipulating the headers underneath 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;
}
Copy the code
let headers = new HttpHeaders({ test: "Hello" })
Copy the code

5. Response content

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

6. The interceptor

Interceptors are the global way to capture and modify HTTP requests and responses in Angular applications. (Token, Error)

Interceptors will only intercept requests made using the HttpClientModule module.

$ ng g interceptor <name>
Copy the code

6.1 Request Interception

@Injectable(a)export class AuthInterceptor implements HttpInterceptor {
  constructor() {}
  // Intercepting methods
  intercept(
    // unknown Specifies the type of the request body
    request: HttpRequest<unknown>,
    next: HttpHandler
     // unknown Specifies the type of the response content
  ): Observable<HttpEvent<unknown>> {
    // Clone and modify the request header
    const req = request.clone({
      setHeaders: {
        Authorization: "Bearer xxxxxxx"}})// The modified request is referred back to the application via a callback function
    return next.handle(req)
  }
}
Copy the code

6.2 Response Interception

@Injectable(a)export class AuthInterceptor implements HttpInterceptor {
  constructor() {}
  // Intercepting methods
  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<any> {
    return next.handle(request).pipe(
      retry(2),
      catchError((error: HttpErrorResponse) = > throwError(error))
    )
  }
}
Copy the code

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}]})Copy the code

7. Angular Proxy

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

    {
         "/api/*": {
            "target": "http://localhost:3070"."secure": false."changeOrigin": true}}Copy the code
    1. /api/: Issued in the application/apiThe initial request goes to this proxy
    2. target: Server sideURL
    3. secure: If the serverURLThe agreement ishttps, this need istrue
    4. changeOrigin: If the server is notlocalhost, this need istrue
  2. Specifying the proxy configuration file (Method 1)

    // package.json
    "scripts": {
      "start": "ng serve --proxy-config proxy.conf.json",}Copy the code
  3. Specify proxy configuration file (Method 2)

    // angular.json file
    "serve": {
      "options": {
        "proxyConfig": "proxy.conf.json"
      },
    Copy the code