javascript - 桌面和移动 Angular 的不同 View

标签 javascript angular mobile

在我正在开发的应用程序中,桌面和移动设备需要完全不同的两种 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对于 Mobilefalse对于 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 也是如此。

尝试访问任何路由的用户将被重定向到正确的路由。

Here is a running example with this suggested solution.

And here is the stackblitz editable version.

关于javascript - 桌面和移动 Angular 的不同 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47550961/

相关文章:

javascript - jQuery 额外的 Ghost div?需要删除功能?

javascript - D3js 没有碰撞的分组散点图

cordova - 用于使用 angular2 构建混合应用程序的框架

javascript - 有没有办法改变移动键盘上的转到/提交按钮在移动网页上的作用?

android - 如何在网页上创建一个 "Send to Mobile"按钮?

JavaScript 监听器不断增加

javascript - 在 Node.js 中,如何使用 node-seq 进行嵌套回调

javascript - 使用键盘输入登录 Angular

unit-testing - Angular2/Jasmine 期望为空会使浏览器崩溃

jquery - 是否有适用于 jQuery Mobile 的 jqueryUi.mouse.js 版本?