使用Google Analytics在位置0的JSON中出现意外的令牌G.

时间:2018-04-02 15:04:32

标签: google-analytics angular5 measurement-protocol

我正在尝试在我的Angular 5项目中使用Google Analytics中的测量协议。我将Google Analytics通用代码放在index.html中,我正在对此服务进行http调用

的index.html

<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'UA-XXXXXXXX-Y', {
      'cookieDomain': 'none'
    });
    // console.log(window.dataLayer);
  </script>

服务启动http调用

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { DataService } from './Data.service';

@Injectable()
export class AnalyticsService {

  private anUID = 'UA-XXXXXXXX-Y';
  private analyticsURL = 'https://www.google-analytics.com/collect?';

  constructor(private http: HttpClient, private datos: DataService) { }

  public pageViewLista(): void {
    this.http.get(
      this.setScreenViewUrl(
        encodeURI('Lista de empresas'))).subscribe((data) => {
          console.log('Received data from GAnalytics: ' + JSON.stringify(data));
        }
    );
  }

  protected setScreenViewUrl (pantalla: string): string {
    const constructUrl = `${this.analyticsURL}v=1&t=screenview&tid=${this.anUID}&cid=${this.datos.id}&an=${this.datos.app}&dt=${pantalla}&cd=${pantalla}`;
    return constructUrl;
  }

}

问题是Google返回一个奇怪的错误,我不知道这意味着什么,也不知道这个错误的原因。我做得不好吗?

Google出错:

  

错误

     

HttpErrorResponse {headers:HttpHeaders,status:200,statusText:“OK”,url:“https://www.google-analytics.com/collect?v=1&t= ...”,ok:false,...}

     

错误:{error:SyntaxError:JSON.parse()位于JSON的JSON中的意外标记G,位于XMLHttp ...,文本:“GIF89a ,D;”}

似乎服务器尝试JSON解析GIF图像。无法在文档中找到任何内容,Google也没有显示任何信息。

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

用于数据收集的Google Analytics端点返回一个透明的gif文件(除了服务器错误之外,它还会返回200状态,因此您无法使用它来查看您的数据是否实际被跟踪)。 gif无法解码为JSON。

如果您需要JSON回复,则需要使用endpoint for the GA debugger(google-analytics.com/debug/collect)。如果你的有效载荷有效,那将提供信息,但不会跟踪呼叫。