Angular 工程源码子应用接入自定义页面示例
🎯 **目标**:快速掌握Angular 20子应用集成
⏱️ **总时间**:30分钟完成3个场景
🚀 场景一:Hello World(10分钟)
目标:一个页面,快速体验集成效果
Step 1: 下载运行
演示工程使用的是angular20 + angular CLI
Bash
git clone https://github.com/lovrabet-ai/sub-app-angular-demo
npm install
ng serveStep 2: 构建部署
Bash
ng build
# 上传dist文件夹到CDN,获得地址:https://your-cdn.com/demo/Step 3: 配置菜单到Lovrabet平台
Plain
菜单名称:Hello World
菜单标识:hello-world
菜单路径:/hello-world
菜单类型:子应用页面
应用入口:https://your-cdn.com/demo/
页面路径:/
状态:启用✅ 成功:点击菜单能看到Hello World页面
📊 场景二:数据展示(15分钟)
目标:在Hello World基础上增加数据接口和图表
Step 1: 切换分支
Bash
git checkout fetch
npm install
ng serveStep 2: 构建部署
Bash
ng build --configuration=production
# 上传到CDN:https://your-cdn.com/demo-fetch/Step 3: 配置2个菜单
菜单1:Hello World页面
Plain
菜单名称:Hello World
菜单标识:hello-world-v2
菜单路径:/hello-world-v2
应用入口:https://your-cdn.com/demo-fetch/
页面路径:/
状态:启用菜单2:数据图表页面
Plain
菜单名称:数据图表
菜单标识:data-chart
菜单路径:/data-chart
应用入口:https://your-cdn.com/demo-fetch/
页面路径:/chart
API权限:✅ 开启
状态:启用✅ 成功:两个菜单都能正常访问,图表页面能显示数据
🔧 场景三:改造已有旧项目(5分钟)
目标:理解技术实现原理
关键技术点
1. Angular 20微前端生命周期
TypeScript
// main.ts 核心代码
export async function mount(props: any) {
// 启动Angular应用
appRef = await bootstrapApplication(AppComponent, appConfig);
}
export async function unmount() {
// 销毁Angular应用
if (appRef) {
appRef.destroy();
}
}2. 路由配置
TypeScript
// app.routes.ts
export const routes: Routes = [
{ path: '', component: HelloWorldComponent }, // 对应菜单页面路径 "/"
{ path: 'chart', component: ChartComponent } // 对应菜单页面路径 "/chart"
];3. API调用
TypeScript
// 使用Angular 20的新HTTP客户端
private http = inject(HttpClient);
getData() {
return this.http.get('https://api.example.com/data');
}4. 构建配置
JSON
// angular.json 关键配置
"configurations": {
"production": {
"outputHashing": "none", // 不使用hash,便于CDN缓存
"vendorChunk": false // 打包成单个文件
}
}核心原理
- 应用启动:平台调用
mount()函数启动Angular应用 - 路由匹配:菜单的"页面路径"对应Angular的路由路径
- 应用销毁:切换菜单时调用
unmount()销毁应用 - 样式隔离:Angular组件样式自动隔离,避免冲突
🎯 关键配置对应关系
Plain
菜单配置中的"页面路径" ←→ Angular路由中的path
/ ←→ { path: '', component: HelloWorldComponent }
/chart ←→ { path: 'chart', component: ChartComponent }一句话总结:菜单页面路径就是Angular路由路径,平台会自动处理应用的加载和卸载。
❓ 常见问题
Q: 为什么需要两个菜单?
A: 一个Angular应用有几个页面就配几个菜单,每个菜单对应一个路由。
Q: API权限什么时候开启?
A: 页面需要调用后端接口时开启。
Q: 页面路径配置错了会怎样?
A: 点击菜单会显示空白页或404错误。
✅ 完成检查
[ ] 场景一:Hello World页面能正常显示
[ ] 场景二:两个菜单都能正常访问
[ ] 场景三:理解了技术原理
恭喜!您已经掌握了Angular 20子应用集成的核心技能。