Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to do Server-side rendering in my Angular application using angular universal. The issue is that I have to apply the isPlatformBrowser() function in the routing.module.ts file also (where I need to pass platformId in the parameter).

I have used this method, to implement server-side rendering in other components and service files.

import { Component, OnInit, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser} from '@angular/common';

@Component({
  selector: 'your-component',
  templateUrl: 'your-component.component.html',
  styleUrls: ['your-component.component.css'],
})
export class YourComponent implements OnInit { 
  constructor(@Inject(PLATFORM_ID) private _platformId: Object) {}

  ngOnInit() {  
    if (isPlatformBrowser(this._platformId)) {
      // here you can access localStorage
    } else {
      // here you are on the server side and localStorage is not available
    }
  }
}

This is my part of app-routing.module.ts where I need to implement server-side rendering

enter image description here

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: isPlatformBrowser(platformId) ? localStorage.getItem('countryCode') : null || 'my'
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled',
      onSameUrlNavigation: 'reload'
    })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

How can I implement server-side rendering in app-routing.module.ts? Can anyone please help me with this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can try to use a RouteGuard to do the redirect:

@Injectable({
  providedIn: 'root'
})
export class RedirectGuard implements CanActivate {
  constructor(@Inject(PLATFORM_ID) private _platformId: Object, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (isPlatformBrowser(this._platformId)) {
      const path = localStorage.getItem('countryCode');
      return this.router.parseUrl(path);
    } else {
      return this.router.parseUrl('/my');
    }
  }
}

And change your routes to this:

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    canActivate: [RedirectGuard]
  }
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...