angularangular-universaldevice-detection

Detecting the device type when an angular universal app pre-rendered on the server


I'm using ngx-device-detector library for detecting the device type (mobile, tablet or desktop). This library working perfectly in client mode but can't detect the device type when an angular universal application pre-rendered on the server(after prerendering on the server, working perfectly on client mode).

  1. I appreciate if someone gives me a solution that works for this library
  2. Eventually, if there isn't any solution for this library, give me another solution

Thanks.


Solution

  • I had a quick look at the code and I think you can call setDeviceInfo with a user agent string that you can retrieve from the request headers

    app.module.ts

    import {Request} from 'express';
    import {REQUEST} from '@nguniversal/express-engine/tokens';
    
    constructor(@Inject(PLATFORM_ID) private platformId, 
                @Optional() @Inject(REQUEST) protected request: Request,
                private deviceService: DeviceDetectorService)
    {
        if(!isPlatformBrowser(platformId))
        {
            this.deviceService.setDeviceInfo(request.headers['user-agent']);
        }
    }