Angular6筆記之封裝http的示例代碼
最近抽空學(xué)習(xí)了一下Angular6,之前主要使用的是vue,所以免不了的也想對(duì)Angular6提供的工具進(jìn)行一些封裝,今天主要就跟大家講一下這個(gè)http模塊。
之前使用的ajax庫是axios,可以設(shè)置baseurl,公共頭部;集中捕捉錯(cuò)誤等,由于Angular6的依賴注入機(jī)制,是不能通過直接修改http模塊暴露的變量來封裝的,但是通過官方文檔我們知道可以通過攔截器(HttpInterceptor) 來實(shí)現(xiàn)這一功能。 攔截器可以攔截請(qǐng)求,也可以攔截響應(yīng),那么通過 攔截請(qǐng)求 就可以實(shí)現(xiàn) 設(shè)置baseurl,公共頭部;而通過 攔截響應(yīng) 就可以實(shí)現(xiàn) 集中捕獲錯(cuò)誤 。廢話不多說,上代碼吧。
第一步:準(zhǔn)備工作,導(dǎo)入 HttpClientModule
在app.module.ts中導(dǎo)入 HttpClientModule,然后在imports數(shù)組中將 HttpClientModule 加入到 BrowserModule 之后,具體代碼為:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
第二步:新建有關(guān)攔截器的文件
在app文件夾下新建http-interceptors文件夾,在其內(nèi)新建base-interceptor.ts,index.ts兩個(gè)文件。其中,base-interceptor.ts是用于設(shè)置攔截器的注入器文件,index.ts則為擴(kuò)展攔截器的提供商。
### 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';
/*設(shè)置請(qǐng)求的基地址,方便替換*/
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}`,
});
/*此處設(shè)置額外的頭部,token常用于登陸令牌*/
if(!req.cancelToken) {
/*token數(shù)據(jù)來源自己設(shè)置,我常用localStorage存取相關(guān)數(shù)據(jù)*/
newReq.headers =
newReq.headers.set('token', 'my-new-auth-token')
}
// send cloned request with header to the next handler.
return next.handle(newReq)
.pipe(
/*失敗時(shí)重試2次,可自由設(shè)置*/
retry(2),
/*捕獲響應(yīng)錯(cuò)誤,可根據(jù)需要自行改寫,我偷懶了,直接用的官方的*/
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 對(duì)象即可攔截請(qǐng)求,而操作 **next.handle(newReq)**的結(jié)果即可攔截響應(yīng)。如果需要修改,可直接擴(kuò)展 base-interceptor.ts 或 參考 base-interceptor.ts 文件新建其他文件,然后在 index.ts 中正確引入該攔截器,并將其添加到 httpInterceptorProviders 數(shù)組中即可。
第三步:注冊(cè)提供商
在app.module.ts中加入以下代碼:
import { httpInterceptorProviders } from './http-interceptors/index'
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
httpInterceptorProviders
],
bootstrap: [AppComponent]
})
至此,Angular6的http模塊封裝已經(jīng)基本完成,如果有需要可以自行擴(kuò)展,可參考第二步。如果看完以后不明白或者我有寫的不對(duì)的地方,歡迎大家進(jìn)行評(píng)論。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 淺談Angular6的服務(wù)和依賴注入
- 基于angular6.0實(shí)現(xiàn)的一個(gè)組件懶加載功能示例
- 在 Angular6 中使用 HTTP 請(qǐng)求服務(wù)端數(shù)據(jù)的步驟詳解
- Angular6中使用Swiper的方法示例
- 詳解Angular6.0使用路由步驟(共7步)
- angular6.0開發(fā)教程之如何安裝angular6.0框架
- 詳解Angular6 熱加載配置方案
- Angular6封裝http請(qǐng)求的步驟詳解
- Angular6 寫一個(gè)簡(jiǎn)單的Select組件示例
- Angular項(xiàng)目如何升級(jí)至Angular6步驟全紀(jì)錄
相關(guān)文章
Angular中封裝fancyBox(圖片預(yù)覽)遇到問題小結(jié)
這篇文章主要介紹了Angular中封裝fancyBox(圖片預(yù)覽)遇到的問題小結(jié),需要的朋友可以參考下2017-09-09
通過AngularJS實(shí)現(xiàn)圖片上傳及縮略圖展示示例
本篇文章主要介紹了通過AngularJS實(shí)現(xiàn)圖片上傳及縮略圖展示,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01
angularjs實(shí)現(xiàn)時(shí)間軸效果的示例代碼
本篇文章主要介紹了angularjs實(shí)現(xiàn)時(shí)間軸效果的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11
妙用Angularjs實(shí)現(xiàn)表格按指定列排序
使用AngularJS的過濾器,可以很容易的實(shí)現(xiàn)在表格中,點(diǎn)擊某一列標(biāo)題進(jìn)行排序,實(shí)現(xiàn)代碼也很簡(jiǎn)單,下面小編給大家分享angularjs實(shí)現(xiàn)表格按指定列排序的實(shí)現(xiàn)代碼,需要的的朋友參考下吧2017-06-06
Angular應(yīng)用prerender預(yù)渲染提高頁面加載速度
這篇文章主要介紹了Angular應(yīng)用prerender預(yù)渲染提高頁面加載速度,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
解決angularjs中同步執(zhí)行http請(qǐng)求的方法
今天小編就為大家分享一篇解決angularjs中同步執(zhí)行http請(qǐng)求的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08
AngularJS 單選框及多選框的雙向動(dòng)態(tài)綁定
本篇文章主要介紹了AngularJS 單選框及多選框的雙向動(dòng)態(tài)綁定的相關(guān)知識(shí)。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-04-04

