Angular 2+ Universal is it possible to pass parameters from expressjs (without using url query string)?

Viewed 2612

I'm using that example to setup Angular 4 Universal with nodejs & expressjs : https://github.com/FrozenPandaz/ng-universal-demo

I've been trying to pass data from the first full page load to the Angular 4 final app.

The use case would be to transfer the language detected from the headers to absorb it from the Angular 4 server renderer so it can use the correct language to translate things.

The only way I've found so far is to do the language detection using HTTP headers from expressjs at the "/" route and redirect with a HTTP 302 to the "/fr" for example if the user language is French.

main.server.ts

app.param('language', function(req: any, res, next, language) {
  if(language.length == 2) 
  {
    req.language = language;
    next();
  } else {
    next(new Error('Invalid language found'));
  }
});

// Redirect incoming trafic without language in url (302 used so the browser do not seal that redirection if the user decides to change language and reload)
app.get('/', function(req, res) {   
  res.set('location', baseUrl + '/' + getLanguage(req);
  res.status(302).send();
});

routes.ts

export const ROUTES: string[] = [
  '/error',
  '/:language',
  '/:language/download'
];

It works, because I'm able to configure the Angular 4 router and retrieve the current route, but it's kind of dirty.

app.module.ts

RouterModule.forRoot([
      { path: '', component: HomeView, pathMatch: 'full'},
      { path: ':language/download', loadChildren: './+lazy/lazy.module#LazyModule'},
      { path: ':language/', redirectTo: ''},
      // Catch all if expressjs allowed this url
      { path: '**', component: HomeView }
    ])

Is there a better way than URL params to pass data from ExpressJS to the Angular 4 app using Angular Universal?

How could I transfer more data (information about the user session for example) from a full load of Angular Universal ?

1 Answers
Related