用户登录
用户注册

分享至

Angular6封装http请求的步骤详解

  • 作者: 武大地
  • 来源: 51数据库
  • 2021-09-24

最近抽空学习了一下angular6,之前主要使用的是vue,所以免不了的也想对angular6提供的工具进行一些封装,今天主要就跟大家讲一下这个http模块。

之前使用的ajax库是axios,可以设置baseurl,公共头部;集中捕捉错误等,由于angular6的依赖注入机制,是不能通过直接修改http模块暴露的变量来封装的,但是通过官方文档我们知道可以通过拦截器(httpinterceptor)来实现这一功能。

拦截器可以拦截请求,也可以拦截响应,那么通过拦截请求就可以实现 设置baseurl,公共头部;而通过拦截响应就可以实现 集中捕获错误 。废话不多说,上代码吧。

第一步:准备工作,导入 httpclientmodule

在app.module.ts中导入 httpclientmodule,然后在imports数组中将 httpclientmodule 加入到 browsermodule 之后,具体代码为:

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则为扩展拦截器的提供商。

### 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://www.51sjk.com/Upload/Articles/1/0/271/271606_20210708052038517.jpg
*/

通过克隆修改 req 对象即可拦截请求,而操作 next.handle(newreq) 的结果即可拦截响应。如果需要修改,可直接扩展 base-interceptor.ts或 参考 base-interceptor.ts 文件新建其他文件,然后在 index.ts 中正确引入该拦截器,并将其添加到 httpinterceptorproviders 数组中即可。

第三步:注册提供商

在app.module.ts中加入以下代码:

import { httpinterceptorproviders } from './http-interceptors/index'
@ngmodule({
 declarations: [
 appcomponent
 ],
 imports: [
 browsermodule,
 httpclientmodule
 ],
 providers: [
 httpinterceptorproviders
 ],
 bootstrap: [appcomponent]
})

第四步,提取baseurl

为了方便后台修改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模块封装已经基本完成,如果有需要可以自行扩展,可参考第二步。

ps:下面看下vue与angular的区别

1.vue仅仅是mvvm中的view层,只是一个如jquery般的工具库,而不是框架,而angular而是mvvm框架。

2.vue的双向邦定是基于es5 中的 getter/setter来实现的,而angular而是由自己实现一套模版编译规则,需要进行所谓的“脏”检查,vue则不需要。因此,vue在性能上更高效,但是代价是对于ie9以下的浏览器无法支持。

3.vue需要提供一个el对象进行实例化,后续的所有作用范围也是在el对象之下,而angular而是整个html页面。一个页面,可以有多个vue实例,而angular好像不是这么玩的。

4.vue真的很容易上手,学习成本相对低,不过可以参考的资料不是很丰富,官方文档比较简单,缺少全面的使用案例。高级的用法,需要自己去研究源码,至少目前是这样。

总结

以上所述是小编给大家介绍的angular6封装http请求的步骤详解,希望对大家有所帮助

软件
前端设计
程序设计
Java相关