angular打包过程遇到的坑
1.打包命令
ng build --prod --aot
2.各种坑
2.1 打包后后静态页面在服务器端无法正常显示 添加路由<router-outlet></router-outlet> 页面首页出现两次渲染情况
路由配置如下:
@NgModule({
imports: [
RouterModule.forRoot([
{ path: '', component: AppComponent},
{ path: 'sign/:openId', component: SignComponent },
{ path: 'suc', component: SucComponent }
])
], exports: [RouterModule]
})
html:
<app-header></app-header>
<router-outlet></router-outlet>
解决方法:
(1)http://blog.csdn.net/catwindboy/article/details/70209872
(2)重定向到自己想要渲染的页面
ps:我照着方法(1)走到一半发现问题依旧存在,过程中还不断出现bug,同事建议我用angular重定向。
2.2 angular重定向踩过的坑
angular重定向 参考的以下几篇文章
(1)重定向配置方法 http://www.cnblogs.com/longhx/p/7238933.html
(2)遇到bug需要写全的: http://blog.csdn.net/huangyezi/article/details/52135339
(3)RouterModule.forRoot用法 https://segmentfault.com/a/1190000009265310
根据第一篇文章和第三篇文章,修改自己的代码为
export const ROUTES: Routes = [
{ path: '', redirectTo: SignComponent},
{ path: 'sign/:openId', component: SignComponent },
{ path: 'suc', component: SucComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(ROUTES)
], exports: [RouterModule]
})
结果报错,然后百度redirectTo用法,看到第二篇文章,redirectTo后面需要添加pathMatch:'full',并且redirectTo后面跟的是路径而不是组件……
再次修改代码
export const ROUTES: Routes = [
{ path: '', redirectTo: '/sign/',pathMatch:'full'},
{ path: 'sign/:openId', component: SignComponent },
{ path: 'suc', component: SucComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(ROUTES)
],
exports: [RouterModule]
})
打包生成静态文件终于可以在tomcat运行
然而,页面刷新向服务器发送请求了……这并不是我想要的
各种百度无果,在angular交流群广发我的问题,终于等到一个回复。
像tomcat 直接用/XX被当成数据请求处理了 加个#号防止向服务器发送请求,所以加个{useHash:true}
问小伙伴从哪里获得消息,答曰:谷歌……
我的电脑貌似好像没有翻墙……所以只能百度
最终修改代码如下,
/路由配置
export const ROUTES: Routes = [
{ path: '', redirectTo: '/sign/',pathMatch:'full'},
{ path: 'sign/:openId', component: SignComponent },
{ path: 'suc', component: SucComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(ROUTES,{useHash:true})
],
exports: [RouterModule]
})
测试开发环境可以,打包后静态文件在tomcat运行也可以,刷新页面也不发请求。