AhsanAyaz / ngx-device-detector

An Angular v7+ library to detect the device, OS, and browser details.
https://ahsanayaz.github.io/ngx-device-detector
MIT License
521 stars 101 forks source link

Incompatibility with @angular/ssr #284

Open mojtabanpe opened 1 year ago

mojtabanpe commented 1 year ago

In Angular 17 the tokens aren't exported anymore by @angular/ssr.

Steps to reproduce the behavior:

  1. Create a new Angular Project with --ssr option.
  2. Create a UnicersalDeviceDetector like in previous versions.
  3. You can not import REQUEST from anywhere.

Expected behavior The project should be compatible with this pull request i think.

mbrdar commented 8 months ago

You can add REQUEST and RESPONSE providers to the server.ts

commonEngine .render({ bootstrap: AppServerModule, documentFilePath: indexHtml, url:${protocol}://${headers.host}${originalUrl}, publicPath: distFolder, providers: [ {provide: APP_BASE_HREF, useValue: baseUrl}, {provide: 'REQUEST', useValue: req}, {provide: 'RESPONSE', useValue: res}, ], }) .then((html) => res.send(html)) .catch((err) => next(err));

And then in your custom DeviceDetectorService you can inject REQUEST like this @Optional() @Inject('REQUEST') request: Request

Full example:

@Injectable() export class SsrDeviceDetectorService extends DeviceDetectorService { constructor(@Inject(PLATFORM_ID) platformId: any, @Optional() @Inject('REQUEST') request: Request) { super(platformId); if (isPlatformServer(platformId)) { super.setDeviceInfo((request.headers['user-agent'] as string) || ''); } } }

Probably only README.MD needs to be updated.