1. HttpClientModule
HttpClientModule
Is http
the service used to handle requests. When using it, you need to introduce and register this module in the root module.
app.module.ts
import {
HttpClientModule} from "@angular/common/http";
@NgModule({
...
imports: [BrowserModule,RouteModule,HttpClientModule],
...
})
(1) HttpClient
Classes need to be introduced in component classes HttpClient
. HttpClient
The request method is implemented in the class HTTP
. You also need to register an HttpClient
instance object of the class for the current component.
import {
HttpClient} from "@angular/common/http";
...
constructor(private http: HttpClient) {
}
Methods on instances can send various http
requests, taking get
requests as an example
this.http.get("https://jsonplaceholder.typicode.com/users").subscribe((res: any) => {
console.log(res);
})
The first parameter is the url address, and the second optional parameter is the configuration object.
get(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'events';
context?: HttpContext;
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType: 'blob';
withCredentials?: boolean;
}): Observable<HttpEvent<Blob>>;
(2) HttpParams
HTTP request body/response body is used to represent serialization parameters, and their MIME types are all application/x-www-form-urlencoded
.
A MIME type ( Multipurpose Internet Mail Extensions Type
) is a way of identifying a file format. Web servers use MIME types to determine how files and content being sent are handled in web browsers.
For example, in the HTTP response header, Content-Type
the field specifies the MIME type of the content returned by this request. Common MIME types are:
text/plain
: text filetext/html
:HTML fileimage/jpeg
:JPEG image fileimage/png
: PNG image fileapplication/pdf
:PDF files
If the web server does not correctly associate the MIME type with the required file, it may cause the web browser to fail to render the page or download the file correctly.
The HttpParams class is defined as follows:
export declare class HttpParams {
constructor (options?: HttpParamsOptions);// 实例化HttpParams类的时候可以传递一个配置对象
has (param: string): boolean;// 判断有没有某个参数
get (param: string): string null;
getAll (param: string): string[] | null;
kefs (): string[];
append (param: string, value: string): HttpParams;
set (param: string, value: string): HttpParams;
delete (param: string, value?: strinq): HttpParams;
toString (): string;
}
append
, set
, delete
methods return new ones HttpParams
, HttpParams
the class is immutable, and every operation that modifies the class will return a new instance.
When creating query parameters, you can pass the class of the configuration object:
export declare interface HttpParamsOptions {
fromString?: string; // 参数以查询参数的方式传递进来
fromObject?: {
// 请求参数以对象的形式传递
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
encoder?: HttpParameterCodec; // 参数中编码特殊字符的方式
}
Query parameters and path parameters are two common ways to pass URL parameters.
Query parameters are a piece of information appended to the URL path, usually starting with a question mark (?), and multiple query parameters are separated by the ampersand (&). For example: https://www.example.com/products?id=123&color=red
The path parameter is the dynamic part located in the URL path, and its format is usually a colon (:) plus the parameter name. For example: https://www.example.com/products/:id, where:id is the path parameter.
Their main differences are:
- Query parameters do not affect which controller or method the request is routed to, while path parameters may.
- Path parameters can only represent a single value, while query parameters can contain multiple values by defining them with the same name.
Only the writing method is different, the performance behavior of the request is the samefromObject
.fromString
let httpParams = new HttpParams({
fromObject: {
name: "zhangsan", age: "18"}});
httpParams = httpParams.set("name", "lisi");
// let httpParams = new HttpParams({fromString: "name=zhangsan&age=18"});
this.http.get("https://jsonplaceholder.typicode.com/users", {
params: httpParams}).subscribe((res: any) => {
console.log(res);
})
(3) HttpHeaders
HttpHeaders
A class is a class that can be used to manipulate request headers. defined in a HttpParams
similar way
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
}
Add a field to the request header:
let headers = new HttpHeaders({
test: "test"});
this.http.get("https://jsonplaceholder.typicode.com/users", {
headers}).subscribe((res: any) => {
console.log(res);
})
(4) Response content
Control the corresponding content through Http
the requested oberve
attributes. observe
There are two optional values for the attribute: body
or response
. When set to body
, what is received in the subscriber is the returned data; when set to , response
what is received in the subscriber is the complete response body.
(5) Interceptor
On the way to sending a request and receiving a response, interceptors can be used to capture and modify http
the request and response globally. Interceptors can intercept HttpClientModule
all requests made by.
1. Create an interceptor
Creating interceptors requires the use of Angular-cli
the provided command line tool: ng g interceptor auth
. Create an auth
interceptor named. After running this code, Angular will create a fileauth.intercepter.ts
in the app directory. This file contains the basic code generated for us. The class is modified and is a service class that needs to implement the interface . Its scope is the entire application. The default method is an interception method and needs to receive two parameters. The first parameter is the request instance that needs to be intercepted. The second parameter is the next object, which represents the next interceptor in the interceptor list. The last object in this linked list is the backend handler, which will send the request to the server and receive the server's response.Angular
AuthInterceptor
@Injectable()
HttpInterceptor
intercept()
next
HttpClient
import {
Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import {
Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request);
}
}
2. Declare the interceptor
Since the interceptor is a service class that acts on the entire application, we need to declare the interceptor at providers in the root module
HTTP_INTERCEPTORS
: a multi-provider token that represents HttpInterceptor
an array of all registered.
multi
: true
option. This required option tells Angular that this HTTP_INTERCEPTORS
is a multi-provider token, meaning it will inject an array of multiple values rather than a single value. Using this attribute eliminates the need to register interceptors one by one.
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
],
3. Modification request
Output in the interceptor request
The request object is immutable. If you want to modify it in the interceptor, you must first clone the current request instance, then modify the properties and pass the new request instance to the next interceptor. In interception, clone()
you can clone the request instance by using the method on the request instance. clone()
The method accepts an object as a parameter, and the attributes set in it will overwrite the original attributes. To set request headers, you can use setHeaders
properties; to change parameters use setParams
properties.
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
let newRequest = request.clone({
setHeaders: {
hello: "angular"
},
setParams: {
name: "wangwu"
}
})
return next.handle(newRequest);
}
4. Modify response
next.handle()
The method returns an instance, and methods and operators Observable
can be used later to operate on the return value. pipe()
For example, you can use an operator to retry the number of times passed to the method retry
when the request fails.retry()
return next.handle(newRequest).pipe(
retry(2)
);
You can write an error in get
the request url
. When requesting, you will make three requests and retry twice.