mzuccaroli / angular-google-tag-manager

A service library for integrate google tag manager in your angular project
https://itnext.io/how-to-add-google-tag-manager-to-an-angular-application-fc68624386e2
MIT License
136 stars 78 forks source link

Angular Universal support, issue browser javascript variables #50

Open CrackerakiUA opened 3 years ago

CrackerakiUA commented 3 years ago

In universal, on node.js back-end we don't have document and window variables, they are undefined. This make below error on universal.

ERROR ReferenceError: document is not defined
    at Object.documentRef (`Path`\main.js:107335:17)
    at GoogleTagManagerService.addGtmToDom (`Path`\main.js:107373:41)
    at GoogleTagManagerService.pushTag (`Path`\main.js:107392:18)
    at SafeSubscriber._next (`Path`\main.js:81712:29)
    at SafeSubscriber.__tryOrUnsub (`Path`\main.js:53361:16)
    at SafeSubscriber.next (`Path`\main.js:53300:22)
    at Subscriber._next (`Path`\main.js:53250:26)
    at Subscriber.next (`Path`\main.js:53227:18)
    at Subject.next (`Path`\main.js:88841:25)
    at SafeSubscriber._next (`Path`\main.js:182123:18)

It can be fixed by setting those variables if they are undefined on below lines https://github.com/mzuccaroli/angular-google-tag-manager/blob/master/projects/angular-google-tag-manager/src/lib/angular-google-tag-manager.service.ts#L12 https://github.com/mzuccaroli/angular-google-tag-manager/blob/master/projects/angular-google-tag-manager/src/lib/angular-google-tag-manager.service.ts#L15

devglrd commented 3 years ago

Pls, can you make a PR ?

CrackerakiUA commented 3 years ago

hey, sorry for late reply, I hope that you have fixed it, I used my clone of your repo, but if that can be solved on Universal level, that will make at least me turn back on your repo. Solution is:

import { PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
...
constructor(private router: Router, @Inject(PLATFORM_ID) private platformId) {
    if(isPlatformServer(this.platformId)){
        this.document = {
            querySelectorAll: ()=>{},
            addEventListener: ()=>{},
            removeEventListener: ()=>{},
            documentElement: {},
            body: {},
        };
    }else{
        this.document = document;
    }
}

And similar for any other global javascript variable. I know also that there is better solution of this with providers, but this is my workout.

onclave commented 2 years ago

Hello, is there any update this this issue?