3

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.

Kamran Taghaddos
  • 452
  • 1
  • 10
  • 22
  • Do you get any error? – David Apr 17 '20 at 07:32
  • No there isn't any error. But can't detect the device type when an angular universal application pre-rendered on the server – Kamran Taghaddos Apr 17 '20 at 09:38
  • Which version are you using? According to github issues, this should work from v 1.4.1 onwards – David Apr 17 '20 at 09:40
  • I use version 1.4.2. In version 1.4.1 the author just adds the "isPlatformBrowser" condition to handle the error only. It hasn't been working for pre-rendering on the server yet to detect device type. – Kamran Taghaddos Apr 17 '20 at 09:46
  • You are right, I did not check the code. Maybe using a library like that? https://hgoebl.github.io/mobile-detect.js/ – David Apr 17 '20 at 09:53
  • @David Can't we use this library by addressing the path of server.ts (e.g. const {ngx-device-detector} = require('./dist/server/main')) in our angular universal express.js server? – Kamran Taghaddos Apr 17 '20 at 10:05
  • Did you already provide the request object to your angular components, from angular universal? – David Apr 17 '20 at 10:19

1 Answers1

5

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']);
    }
}
Kamran Taghaddos
  • 452
  • 1
  • 10
  • 22
David
  • 33,444
  • 11
  • 80
  • 118