在我正在开发的应用程序中,桌面和移动设备需要完全不同的两种 View 。不可能使用 CSS,因为内容完全不同。
我做了什么?
我已经在 Routing file
中检查过它是否是桌面版/移动版 使用代码 const isMobile = window.innerWidth < 768;
在路径组件中:component: isMobile ? MobileComponent : DesktopComponent
这在开发环境中运行良好。但是在生产构建时失败了 ng serve --prod
(显然是 Angular 5)
问题:
完全没有错误,根据 isMobile
true/false 它应该加载 MobileComponent/DesktopComponent。但即使 isMobile 为 true/false,它也不会加载
始终在桌面和移动设备中加载 MobileComponent。同时isMobile
值计算正确,true
对于 Mobile
和 false
对于 Desktop
我认为原因是路由在发送给客户端之前已经编译好了。
解决方法已尝试但无效:
在计算 isMobile
时使用了 if..else 条件并在路由文件中给出该变量(组件)而不是三元运算
任何方式:
有什么方法可以实现同样的功能吗?
提前致谢
最佳答案
正如我在问题评论部分所说,路由守卫将是一个很好的解决方案。
MobileGuard
看起来像这样:
export class MobileGuard implements CanActivate {
constructor(private _router: Router, private _mobileService: MobileService) {}
canActivate(): boolean {
const isMobile = this._mobileService.isMobile();
if(!isMobile) {
this._router.navigate(['/desktop']);
}
return isMobile;
}
}
DesktopGuard
也是如此。
尝试访问任何路由的用户将被重定向到正确的路由。
关于javascript - 桌面和移动 Angular 的不同 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47550961/