Angular (角度)移动和桌面视图以及SSR的不同组件
我正试图开发一个网站,其中有两个完全不同的桌面和移动视图。我通过使用基于设备宽度的不同路由机制来实现它。这里有一个例子Angular (角度)移动和桌面视图以及SSR的不同组件,angular,Angular,我正试图开发一个网站,其中有两个完全不同的桌面和移动视图。我通过使用基于设备宽度的不同路由机制来实现它。这里有一个例子 import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; let routes : Routes = []; if (window.innerWidth < 768) { routes = [ {path: '', c
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
let routes : Routes = [];
if (window.innerWidth < 768) {
routes = [
{path: '', component: MobileComponent},
// ...
];
} else {
routes = [
{path: '', component: DesktopComponent},
// ...
];
}
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
从'@angular/core'导入{NgModule};
从'@angular/router'导入{Routes,RouterModule};
let routes:routes=[];
如果(窗内宽度<768){
路线=[
{路径:'',组件:MobileComponent},
// ...
];
}否则{
路线=[
{路径:'',组件:DesktopComponent},
// ...
];
}
@NGD模块({
导入:[RouterModule.forRoot(路由)],
导出:[路由模块]
})
导出类AppRoutingModule{}
但对于SSR应用程序,我不应该使用窗口变量。
如何使用SSR获得相同的结果?Angular SSR从服务器为应用程序提供服务。服务器没有窗口对象 所以你需要检测平台。平台可以是服务器或浏览器。此处
isPlatformBrowser
可用于检测浏览器
因此,在服务中创建一个基于平台返回布尔值的方法
服务.ts
import { Inject, Injectable, } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class PlatformService {
isBrowser: boolean;
constructor( @Inject(PLATFORM_ID) platformId: Object) {
this.isBrowser = isPlatformBrowser(platformId);
}
isPlatformBrowser() { // use this method to detect platform
return this.isBrowser;
}
}
然后在路由文件中使用该方法
if (platformSerivce.isPlatformBrowser && window.innerWidth < 768) {
routes = [
{path: '', component: MobileComponent},
// ...
];
}
if(platformSerivce.isPlatformBrowser&&window.innerWidth<768){
路线=[
{路径:'',组件:MobileComponent},
// ...
];
}
试试这个我已经试过了,但是这导致了窗口。innerWidth
为未定义的。我不知道谁投了反对票,也不知道为什么答案被否决,这让我对该方法有了一个想法。但我一直坚持在路由模块中使用服务方法。能否请您提供我,路由模块完整的源代码,请!。你需要在路由器文件中导入PlatformService,然后调用PlatformService.isPlatformBrowserNo这不起作用,我怎么能导入一个服务,我需要正确地注入它?我已经尝试了你说的方法,但它不起作用。但是,当我在app.component.ts
文件中使用它时,它可以完美地工作。我将扩展此方法,将其用作路线守卫,也许它会起作用