最近抽空学习了一下Angular6,以前主要使用的是vue,因此免不了的也想对Angular6提供的工具进行一些封装,今天主要就跟你们讲一下这个http模块。
以前使用的ajax库是axios,能够设置baseurl,公共头部;集中捕捉错误等,因为Angular6的依赖注入机制,是不能经过直接修改http模块暴露的变量来封装的,可是经过官方文档咱们知道能够经过拦截器(HttpInterceptor)来实现这一功能。html
拦截器能够拦截请求,也能够拦截响应,那么经过拦截请求就能够实现 设置baseurl,公共头部;而经过拦截响应就能够实现 集中捕获错误 。废话很少说,上代码吧。vue
在app.module.ts中导入 HttpClientModule,而后在imports数组中将 HttpClientModule 加入到 BrowserModule 以后,具体代码为:ios
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, // import HttpClientModule after BrowserModule. HttpClientModule, ], declarations: [ AppComponent, ], bootstrap: [ AppComponent ] })
在app文件夹下新建http-interceptors文件夹,在其内新建base-interceptor.ts,index.ts两个文件。其中,base-interceptor.ts是用于设置拦截器的注入器文件,index.ts则为扩展拦截器的提供商。ajax
### base-interceptor.ts 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'; /*设置请求的基地址,方便替换*/ const baseurl = 'http://localhost:8360'; @Injectable() export class BaseInterceptor implements HttpInterceptor { constructor() {} intercept(req, next: HttpHandler) { let newReq = req.clone({ url: req.hadBaseurl ? `${req.url}` : `${baseurl}${req.url}`, }); /*此处设置额外的头部,token经常使用于登录令牌*/ if(!req.cancelToken) { /*token数据来源本身设置,我经常使用localStorage存取相关数据*/ newReq.headers = newReq.headers.set('token', 'my-new-auth-token') } // send cloned request with header to the next handler. return next.handle(newReq) .pipe( /*失败时重试2次,可自由设置*/ retry(2), /*捕获响应错误,可根据须要自行改写,我偷懒了,直接用的官方的*/ catchError(this.handleError) ) } private handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } // return an observable with a user-facing error message return throwError( 'Something bad happened; please try again later.'); }; } ### index.ts 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 http://angular.io/license */
经过克隆修改 req 对象便可拦截请求,而操做 next.handle(newReq)的结果便可拦截响应。若是须要修改,可直接扩展 base-interceptor.ts或 参考 base-interceptor.ts 文件新建其余文件,而后在 index.ts 中正确引入该拦截器,并将其添加到 httpInterceptorProviders 数组中便可。bootstrap
在app.module.ts中加入如下代码:axios
import { httpInterceptorProviders } from './http-interceptors/index' @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [ httpInterceptorProviders ], bootstrap: [AppComponent] })
为了方便后台修改baseurl,咱们能够将baseurl提取为全局变量,在index.html中进行设置,数组
# index.html 增长 <script> window.baseurl = "http://localhost:8360" </script> # base-interceptor.ts 修改 const baseurl = window.baseurl;
这样一来,若是后台要修改的话,只需修改index.html中的变量便可,无需再次编译。还有,像这些后期可能更改的变量,建议是直接放在index.html中,由于缓存的缘由,若是放在js文件中再引入的话,文件并不能及时更新或是每次都须要更改文件名,会致使没必要要的麻烦。缓存
至此,Angular6的http模块封装已经基本完成,若是有须要能够自行扩展,可参考第二步。若是看完之后不明白或者我有写的不对的地方,欢迎你们在下方进行评论。app