You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular15中替代已废弃gAPI获取Google Analytics访客数方案咨询

替代gAPI在Angular 15中获取Google Analytics访客数的方案

问题背景

原使用gapi库实现Google认证并调用Analytics API时,收到弃用提示:

{"error":"idpiframe_initialization_failed","details":"You have created a new client application that uses libraries for user authentication or authorization that are deprecated. New clients must use the new libraries instead. See the Migration Guide for more information."}

原代码依赖已弃用的gapi.client.init方法,需替换为**Google Identity Services (GIS)**实现认证,再通过Angular的HttpClient调用Analytics Data API获取访客数据。

解决方案步骤

1. 引入Google Identity Services脚本

在项目根目录的index.html中添加GIS客户端脚本:

<script src="https://accounts.google.com/gsi/client" async defer></script>

2. 实现认证逻辑(替换原initGoogleOAuth)

在Angular组件中,使用GIS的google.accounts.oauth2.initTokenClient方法完成认证,获取访问令牌:

import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment';

constructor(private http: HttpClient) {}

initGoogleOAuth() {
  const { clientId } = environment.googleAnalytics;

  // 初始化Token客户端
  const tokenClient = google.accounts.oauth2.initTokenClient({
    client_id: clientId,
    scope: 'https://www.googleapis.com/auth/analytics.readonly',
    callback: (tokenResponse) => {
      if (tokenResponse.error !== undefined) {
        throw tokenResponse;
      }
      // 认证成功后调用数据获取方法
      this.getAnalyticsData('2023-01-01', 'today', tokenResponse.access_token);
    },
  });

  // 检查是否已有有效令牌,无则触发授权弹窗
  tokenClient.requestAccessToken({ prompt: '' });
}

3. 调用Analytics Data API获取访客数

使用Angular的HttpClient直接请求API,替代原gapi.client调用:

getAnalyticsData(startDate: string, endDate: string, accessToken: string) {
  const apiUrl = 'https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}/runReport';
  // 替换{PROPERTY_ID}为你的Google Analytics 4属性ID
  const formattedUrl = apiUrl.replace('{PROPERTY_ID}', environment.googleAnalytics.propertyId);

  const requestBody = {
    dateRanges: [{ startDate, endDate }],
    metrics: [{ name: 'activeUsers' }] // 对应网站访客数指标,可按需调整
  };

  this.http.post(formattedUrl, requestBody, {
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    }
  }).subscribe({
    next: (response: any) => {
      // 提取并处理访客数据
      const visitorCount = response.rows?.[0]?.metricValues?.[0]?.value || '0';
      console.log('总访客数:', visitorCount);
      // 在这里将数据绑定到页面展示
    },
    error: (err) => {
      console.error('获取数据失败:', err);
    }
  });
}

4. 环境变量配置

确保environment.ts中包含所需配置项:

export const environment = {
  production: false,
  googleAnalytics: {
    clientId: '你的OAuth客户端ID',
    propertyId: '你的GA4属性ID'
  }
};

关键说明

  • 必须使用Google Identity Services完成认证,这是Google当前唯一推荐的OAuth2.0认证方案
  • 需在Google Cloud Console中启用Analytics Data API,并确保OAuth客户端已配置analytics.readonly权限
  • 若需其他数据(如页面浏览量),可修改请求体中的metrics字段,参考GA4官方指标列表调整

内容的提问来源于stack exchange,提问作者Jihen BENMUSTAPHA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:45:36