I recently took the time to learn about Angular6. I used to mainly use vue, so I inevitably wanted to encapsulate the tools provided by Angular6. Today I will mainly talk to you about this http module.
The ajax library used before was axios, which can set baseurl, public headers, and centrally catch errors. Due to the dependency injection mechanism of Angular6, it cannot be encapsulated by directly modifying the variables exposed by the http module, but through the official documentation, we know that it can be encapsulated throughInterceptor (HttpInterceptor)To implement this function.
The interceptor can intercept requests or intercept responses, so by intercepting the request, you can set the baseurl and the public header; and by intercepting the response, you can achieve centralized capture of errors. Without further ado, please add the code.
Step 1: Preparation, import HttpClientModule
After importing the HttpClientModule in the imports array, add the HttpClientModule to the BrowserModule, the specific code is:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, // import HttpClientModule after BrowserModule. HttpClientModule, ], declarations: [ AppComponent, ], bootstrap: [ AppComponent ] })
Step 2: Create a new file about the interceptor
Create a new http-interceptors folder under the app folder, and create two new files inside it. Among them, it is the injector file used to set the interceptor, and it is the provider of the extended interceptor.
### import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http'; import { throwError } from 'rxjs' import { catchError, retry } from 'rxjs/operators'; /*Set the requested base address to facilitate replacement*/ const baseurl = 'http://localhost:8360'; @Injectable() export class BaseInterceptor implements HttpInterceptor { constructor() {} intercept(req, next: HttpHandler) { let newReq = ({ url: ? `${}` : `${baseurl}${}`, }); /*Add extra header here, token is often used for login tokens*/ if(!) { /* Set the source of the token data by myself, I often use localStorage to access related data*/ = ('token', 'my-new-auth-token') } // send cloned request with header to the next handler. return (newReq) .pipe( /*Try again twice when it fails, and you can set it freely*/ retry(2), /*Catch the response error, you can rewritten it yourself as needed. I was lazy and used the official one directly*/ catchError() ) } private handleError(error: HttpErrorResponse) { if ( instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. ('An error occurred:', ); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, ( `Backend returned code ${}, ` + `body was: ${}`); } // return an observable with a user-facing error message return throwError( 'Something bad happened; please try again later.'); }; } ### import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { BaseInterceptor } from './base-interceptor'; /** Http interceptor providers in outside-in order */ export const httpInterceptorProviders = [ { provide: HTTP_INTERCEPTORS, useClass: BaseInterceptor, multi: true }, ]; /* Copyright 2017-2018 Google Inc. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at /license */
Requests can be intercepted by cloning and modifying req objects, and the result of the operation (newReq) can intercept the response. If you need to modify it, you can directly expand or reference the file to create another file, then correctly introduce the interceptor in , and add it to the httpInterceptorProviders array.
Step 3: Register a provider
Add the following code to:
import { httpInterceptorProviders } from './http-interceptors/index' @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [ httpInterceptorProviders ], bootstrap: [AppComponent] })
Step 4: Extract baseurl
In order to facilitate the modification of baseurl in the background, we can extract baseurl as a global variable and set it in it.
# Increase<script> = "http://localhost:8360" </script> # Reviseconst baseurl = ;
In this way, if you want to modify the background, you only need to modify the variables, without compiling them again. Also, it is recommended to place variables like these that may be changed later in the process. Due to caching, if placed in the js file and introduced, the file cannot be updated in time or the file name needs to be changed every time, which will cause unnecessary trouble.
At this point, the packaging of Angular6's http module has been basically completed. If you need it, you can expand it yourself. You can refer to the second step.
ps: Let's take a look at the difference between vue and angular
It's just the view layer in mvvm, it's just a tool library like jquery, not a framework, and angular is an mvvm framework.
The two-way bond is implemented based on getter/setter in ES5, while angular implements a set of template compilation rules by itself, requiring so-called "dirty" checks, and vue does not. Therefore, vue is more efficient in performance, but at the cost of not being supported by browsers below ie9.
An el object needs to be provided for instantiation, and all subsequent scopes of action are also below the el object, and angular is the entire html page. A page can have multiple vue instances, and angular seems to be not played like this.
It is really easy to get started, and the learning cost is relatively low, but the information you can refer to is not very rich, the official documents are relatively simple, and there is a lack of comprehensive use cases. Advanced usage requires you to study the source code yourself, at least for now.
Summarize
The above is a detailed explanation of the steps for encapsulating http requests for Angular6 introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!