Skip to content

Commit

Permalink
✨ 新增请求地址拦截器
Browse files Browse the repository at this point in the history
  • Loading branch information
inlym committed Nov 18, 2023
1 parent e13f6a6 commit 3ea61ab
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 7 deletions.
4 changes: 3 additions & 1 deletion src/app/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { ApplicationConfig } from '@angular/core'
import { provideRouter } from '@angular/router'

import { routes } from './app.routes'
import { provideHttpClient, withInterceptors } from '@angular/common/http'
import { urlInterceptor } from './common/interceptors/url.interceptor'

export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
providers: [provideRouter(routes), provideHttpClient(withInterceptors([urlInterceptor]))],
}
12 changes: 12 additions & 0 deletions src/app/common/core/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,15 @@ export const storage = localforage.createInstance({
name: 'lifehelper',
storeName: environment.name,
})

// ================ 使用说明 ================
// 所有缓存均需要在此处注册再使用,方便统一管理
// ========================================

export enum StorageItem {
/** 用户登录鉴权凭证 */
TOKEN = 'token',

/** 用户信息 */
USER_INFO = 'user_info',
}
19 changes: 19 additions & 0 deletions src/app/common/interceptors/url.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { HttpInterceptorFn } from '@angular/common/http'
import { environment } from '../../../environments/environment'

/** 请求地址前缀 */
const { baseURL } = environment

/**
* 请求地址拦截器
*
* ### 主要用途
* 根据当前环境在请求路径加上请求地址前缀。
*/
export const urlInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.startsWith('http://') || req.url.startsWith('https://')) {
return next(req)
} else {
return next(req.clone({ url: baseURL + req.url }))
}
}
15 changes: 9 additions & 6 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>LifeHelperWeb</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<meta charset="utf-8">
<title>小鸣助手</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
<app-root></app-root>
<app-root></app-root>
</body>

</html>

0 comments on commit 3ea61ab

Please sign in to comment.