Angular6中怎么封裝http請求,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
第一步:準備工作,導入 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]
})第四步,提取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請求問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。