桌面和移动Angular的不同视图

Har*_*n N 5 javascript mobile angular

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

我做了什么?

我已经在Routing file使用代码检查过它是否是台式机/手机const isMobile = window.innerWidth < 768;

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

这在开发环境中运行良好。但是,尽管生产构建失败了ng serve --prod(显然是Angular 5)

问题:

完全没有错误,根据对isMobile/错,它应该加载MobileComponent / DesktopComponent。但是即使isMobile为true / false,也不会加载

始终在桌面和移动设备中加载MobileComponent。而isMobile价值是越来越计算正确,trueMobilefalseDesktop

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

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

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

任何方式:

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

提前致谢

Car*_*Dry 10

不要使用 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)
      }
    }
}
Run Code Online (Sandbox Code Playgroud)


Jir*_*vec 10

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

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

最后,您始终可以使用UserAgent检测。为此,请参阅此线程/sf/answers/967347741/

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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


ibe*_*oun 8

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于DesktopGuard.

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

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

这是 stackblitz 可编辑版本。


Viv*_*mar 5

直接对路线进行更改,如下所示 -

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

Run Code Online (Sandbox Code Playgroud)