Error: gtag is not defined in angular 8 project

Error: gtag is not defined in angular 8 project

我在 angular 8 工作并添加了 google 分析,以便为用户提供更好的服务。但它不断显示以下错误:

添加以下服务以在项目中使用 google 分析:

gaservice.service.ts

import { Injectable } from '@angular/core';

declare let gtag:Function;
@Injectable({
  providedIn: 'root'
})
export class GoogleAnalyticsService {
  constructor(){}

  public eventEmitter( 
    eventCategory: string, 
    eventAction: string, 
    eventLabel: string = null,  
    eventValue: number = null ){ 
               gtag('event', eventAction, {
                'event_category': eventCategory,
                'event_label': eventLabel,
                'value': eventValue
              });
    }
}

使用

(<any>window).gtag(..)

window['gtag'](...)

我想我可以做的是创建一个函数:

export const gtag = () => window['dataLayer'].push(arguments)

这是因为我将 GTM 与 GA4 一起使用,但它没有为我定义 window.gtag(参见 )。