Angular6笔记之封装http

栏目: 编程语言 · AngularJS · 发布时间: 7年前

内容简介:最近抽空学习了一下Angular6,之前主要使用的是vue,所以免不了的也想对Angular6提供的工具进行一些封装,今天主要就跟大家讲一下这个http模块。之前使用的ajax库是axios,可以设置baseurl,公共头部;集中捕捉错误等,由于Angular6的依赖注入机制,是不能通过直接修改http模块暴露的变量来封装的,但是通过官方文档我们知道可以通过在app.module.ts中导入 HttpClientModule,然后在imports数组中将 HttpClientModule 加入到 Brow

最近抽空学习了一下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://angular.io/license
*/
复制代码

通过克隆修改 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]
})

复制代码

至此,Angular6的http模块封装已经基本完成,如果有需要可以自行扩展,可参考第二步。如果看完以后不明白或者我有写的不对的地方,欢迎大家在下方进行评论。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Building Social Web Applications

Building Social Web Applications

Gavin Bell / O'Reilly Media / 2009-10-1 / USD 34.99

Building a social web application that attracts and retains regular visitors, and gets them to interact, isn't easy to do. This book walks you through the tough questions you'll face if you're to crea......一起来看看 《Building Social Web Applications》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码