-1

I am trying to develop a website which has two completely different views for Desktop and Mobile. I achieved it by using different routing mechanism based upon device width. Here is an example.

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 { }

But for SSR application, I am not supposed to use window variables. How can I achieve the same result along with SSR?

1 Answers1

0

Angular SSR serves the app from the server. And server does not have window object.

So you need to detect platform. Platform can be either server or browser. And here isPlatformBrowser can be used here to detect browser.

So make a method in the service to return Boolean value based on the platform.

service.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;
  }         

}

And then use that method in your routing file

if (platformSerivce.isPlatformBrowser && window.innerWidth < 768) {
   routes = [
    {path: '', component: MobileComponent},
     // ...
   ];
}
Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52
  • I don't know who down voted, and why the answer has been down voted, It has given me an idea about the approach. But am stuck at using service method in Routing Module. Can you please provide me, routing module complete source, please!. – Sankeerth Mahurkar Dec 20 '19 at 13:13
  • You need to import PlatformService in router file and then just call PlatformService.isPlatformBrowser – Surjeet Bhadauriya Dec 20 '19 at 13:16
  • No this is not working, how can I just import a service, I need to inject it right ?I Have tried the method you said but it is not working. However it works perfectly when I use it in `app.component.ts` file. I would extend this method to use it as route guard, might be it will work – Sankeerth Mahurkar Dec 20 '19 at 13:32