node.jsangularexpressangular2-universal

Get vaues from ExpressJS in Angular Universal app


I'm building an Angular2 Universal app and I'm integrating ng2-translate.

Server side I need to know the language of the user, which I could get from ExpressJS via request.acceptsLanguages() (see docs).

I do correctly get these values in server.ts like so:

function ngApp(req: any, res: any) {
  let supportedLangs = req.acceptsLanguages();
  console.log('supportedLangs', supportedLangs);
  res.render('index', {
    req,
    res,
    ngModule: AppModule,
    preboot: false,
    baseUrl: '/',
    requestUrl: req.originalUrl,
    originUrl: req.hostname
  });
}

Then I don't know how to pass them, or access them, in my app.node.module.ts where I set up ng2-translate for the server.

Is there a way to access these values from the Angular Universal app (server side)? How?


Solution

  • For those interested, the solution is to use Zone, and when doing so there are some things to be aware of.

    First, to make sure that the TypeScript parser does not break, you need to also declare,at the top of the file in which you are using Zone:

    declare var Zone: any;
    

    Or I guess you may install all the typings, but I have not tested that.

    Then, anywhere in the node only modules you can get the parameters passed to res.render in the server.ts file by doing this:

    let req = Zone.current.get('req');
    

    Finally, you can access any of the properties passed to req in server.ts, e.g.:

    req.headers['user-agent'];
    

    UPDATE FOR ANGULAR 5

    As pointed out in the comments, the previous code does not work anymore. The good news is that with Angular 5 is much easier and straightforward:

    import { Injector } from '@angular/core';
    import { REQUEST } from '@nguniversal/express-engine/tokens';
    
    constructor(
        private _injector: Injector
    ) {
        const req = this._injector.get(REQUEST);
        // use as: req.headers['whatever-is-in-the-headers']
    }