我有一个大问题。我尝试了许多没有结果的解决方案:(我想根据屏幕大小加载一个模块来查看移动视图或web视图。
最接近我目标的是那个代码,但它有很多错误。
当屏幕是<768
时,我设置http://localhost:4200/
加载网络,但也可以移动=(
当屏幕是>768
并且我设置http://localhost:4200/
加载web时。=(
当屏幕是<768
并且我设置http://localhost:4200/mobile/etc/etc/etc
时,加载mob和web并重定向到http://localhost:4200/mobile
=(
当屏幕是>768
并且我设置http://localhost:4200/web/etc/etc/etc
加载web时。=(
app-routing.module.ts
const routes: Routes = [
{
path: 'mobile',
loadChildren: './view/mobile/mobile.module#MobileModule',
canActivate: [MobGuardService],
data: {
preload: false
}
},
{
path: 'web',
loadChildren: './view/web/web.module#WebModule',
canActivate: [WebGuardService],
data: {
preload: false
}
},
{
path: 'error',
loadChildren: './view/error/error.module#ErrorModule',
data: {
preload: false
}
},
{
path: '',
redirectTo: window.innerWidth < 768 ? `/mobile/etc/etc/etc` : `/web/etc/etc/etc`,
pathMatch: 'full'
},
{
path: '**',
redirectTo: window.innerWidth < 768 ? `/mobile/etc/etc/etc` : `/web/etc/etc/etc`
}
];
mob-guard.services.ts
@Injectable({
providedIn: 'root'
})
export class MobGuardService implements CanActivate {
constructor(
private router: Router
) {
}
canActivate() {
if (window.innerWidth >= 768) {
this.router.navigate(['/']).then();
return false;
}
return true;
}
}
web-guard.service.ts
@Injectable({
providedIn: 'root'
})
export class WebGuardService implements CanActivate {
constructor(
private router: Router
) {
}
canActivate() {
if (window.innerWidth < 768) {
this.router.navigate(['/m/']).then();
return false;
}
return true;
}
}
我的目标很简单,但我不知道如何做到:
- 当屏幕为'<768',并将localhost:4200 rediretTo和仅加载模块mobile
- 当屏幕为'>768',并将localhost:4200 rediretTo和仅加载模块web
- 当屏幕是'<768’,并将localhost:4200/mobile/etc/etc/etc rediretTo和仅加载模块mobile
- 当屏幕为'>768',并将localhost:4200/mobile/etc/etc/etc仅加载模块web,但重定向到localhost:4200/web/etc/etc
- 当屏幕是'<768',并将localhost:4200/web/etc/etc/etc仅加载模块mob,但重定向到localhost:4200/mobile/etc/etc
我试图实现这样的东西,但dosent有效:
{
path: window.innerWidth < 768 ? 'm' : 'w',
loadChildren: window.innerWidth < 768 ? './view/mob/mob.module#MobModule' : './view/web/web.module#WebModule',
canActivate: window.innerWidth < 768 ? [MobGuardService] : [WebGuardService],
data: {
preload: false
}
}
我希望得到帮助。谢谢你抽出时间。
您可以制作一个单根组件,在其中添加一个检查窗口内部宽度的检查,并相应地重定向您的窗口视图或移动视图。
@component({
selector:'app-home',
template:'',
})
constructor(private rout:router){
if(window.innerWidth>768){
this.rout.navigate(['/window'])
}else{
this.rout.navigate(['/mobile'])
}
}
我想这可能适用于角度9+
{
path: '',
loadChildren: () => window.innerWidth < 768 ? import(`/mobile/etc/etc/etc`).then(m => m.MobileModule) : import(`/web/etc/etc/etc`).then(m => m.WebModule),
pathMatch: 'full'
}