繁体   English   中英

桌面和移动 Angular 的不同视图

[英]Different views for Desktop and mobile Angular

在我正在开发的应用程序中,它需要完全不同的两种不同的桌面视图和移动视图。 不可能使用 CSS,因为内容完全不同。

我做了什么?

我已经使用代码const isMobile = window.innerWidth < 768;Routing file检查了它是否是桌面/移动设备const isMobile = window.innerWidth < 768;

在路径组件中: component: isMobile ? MobileComponent : DesktopComponent component: isMobile ? MobileComponent : DesktopComponent

这在开发环境中完美运行。 但是当生产构建这失败ng serve --prod (显然是 Angular 5)

问题:

根本没有错误,根据isMobile true/false,它应该加载 MobileComponent/DesktopComponent。 但即使 isMobile 为真/假,它也不会加载

始终在桌面和移动设备中加载 MobileComponent。 虽然isMobile值计算正确, MobiletrueDesktopfalse

我认为原因是路由在发送到客户端之前已经编译好了。

解决方法已尝试但不起作用:

使用 if..else 条件,同时计算isMobile并在路由文件中给出该变量(组件)而不是三元运算

反正:

有什么方法可以用来实现相同的功能吗?

提前致谢

正如我在问题评论部分所说的,路由守卫将是一个很好的解决方案。

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

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

以下是此建议解决方案的运行示例。

这是 stackblitz 可编辑版本。

不要使用 canActivate 或路由守卫,因为它们需要用于身份验证等。

新方法:

{
    path: 'your-path',
    loadChildren: () => {
      if(window.innerWidth > 768 ) {
        return import('./your-desktop.module').then(m => m.YourDesktopModule)
      } else {
        return import('./your-mobile.module').then(m => m.YourMobileModule)
      }
    }
}

像这样直接改变路线 -

const routes: Routes = [{
  path: '',
  component:  window.screen.width > 767 ? WelcomeDesktopComponent : WelcomeMobileComponent
}];

我同意@CarbonDry 在 RoutingModule 中使用逻辑是最好的方法。 但是我认为使用窗口大小是一种检测设备类型的糟糕方法。 当然,这取决于用例 - 如果您只需要为小屏幕显示不同的 UI, window.innerWidth就可以了。 如果您想为手机提供单独的功能,那可能还不够。

您可以通过多种方式检查设备类型,例如您可以使用navigator.orientation === undefined来检查设备是否为桌面设备(因为桌面设备不支持navigator.orientation

最后,您始终可以使用UserAgent检测。 为此,请参阅此线程https://stackoverflow.com/a/13819253/8775880

所以最后,你的代码可能看起来像这样

const isDesktop(): boolean => {
   return navigator.orientation === undefined;
}

{
    path: 'path',
    loadChildren: () => {
      if(isDesktop())
        return import('./desktop.module').then((m) => m.DesktopModule);
      return import('./mobile.module').then((m) => m.MobileModule);
    }
}

编辑请记住,当第一次加载路径时, loadChildren只会运行一次。 因此,您可能需要考虑简单地检查屏幕尺寸。 假设768px适用于手机上的纵向,但如果我以横向模式打开网站呢? 在某些情况下,即使是横向模式也需要移动 UI。 但是如果你只检查客户端宽度,你会得到桌面版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM