Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

angular - How to use a variable from one module to other module

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

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

1 Reply

0 votes
by (71.8m points)

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]
  }
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...