主细节响应页面

时间:2017-09-18 17:09:26

标签: angular angular2-routing

我正在寻找一种方法来为移动和桌面分辨率设置不同的路由。我有详细的页面布局。因此,当用户移动到移动设备时,用户应该看到主列表&当用户单击列表的项目时,它应该导航到详细信息页面。我想桌面和移动设备将有2套路由。我需要根据宽度加载正确的路由配置。

请建议。

对于桌面:

  const appDesktopRoutes:Routes =[
         {
            path: '',
            component: ItemListComponent,
            children: [
                {
                    path: 'item/:id',
                    component: ItemDetailsComponent
                }
            ]
        }]  

对于手机:

const appMobileRoutes:Routes =[
    {
        path: '',
        component: ItemListComponent,
    },
     {
        path: 'item/:id',
        component: ItemDetailsComponent
    }
]

1 个答案:

答案 0 :(得分:3)

您可以获得如下所示的窗口宽度,一旦拥有它们,您可以使用它来隐藏模板中的详细信息组件,并更新您的详细信息列表单击行为,以在相同页面中导航而不是打开。

export class AppComponent {

  constructor(ngZone: NgZone) {
    // Initial draw
    this.drawPage(window.innerWidth);

    // On resize
    window.onresize = (e) => {
      ngZone.run(() => {
       this.drawPage(window.innerWidth);
      });
    };
  }

  drawPage(width){
    // use width to determine how to draw.
  }
}

<强>更新

您需要根据宽度重置路线。

尝试以下,

创建一个可以为您提供窗口宽度的分辨率服务

ResolutionService

@Injectable()
export class ResolutionService {
  constructor(ngZone: NgZone) {
    // On resize
    window.onresize = (e) => {
      ngZone.run(() => {
        this.width.next(window.innerWidth);
      });
    };
  }

  width: BehaviorSubject<number> = new BehaviorSubject<number>(window.innerWidth);
}

在您的RouterModule中使用以上服务重置路由,如下所示

AppRoutingModule

const appDesktopRoutes: Routes = [
  {
    path: '',
    component: ItemListComponent,
    children: [
      {
        path: 'item/:id',
        component: ItemDetailsComponent
      }
    ]
  }
];

const appMobileRoutes: Routes = [
  {
    path: '',
    component: ItemListComponent,
  },
  {
    path: 'item/:id',
    component: ItemDetailsComponent
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appDesktopRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {
  MOBILE_WIDTH = 500;
  constructor(router: Router, resolutionService: ResolutionService) {

    // subscribe to resolution service to get current width
    resolutionService.width.subscribe(width => {
      if (width < this.MOBILE_WIDTH) {
        router.resetConfig(appMobileRoutes);
      } else {
        router.resetConfig(appDesktopRoutes);
      }
    });

  }
}

这是example Plunker !!

希望这会有所帮助!!