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

API密钥出错时如何隐藏Google Places API报错框并捕获相关错误?

Angular + ngx-google-places-autocomplete 捕获Google API错误方案

以下方案可覆盖你提到的账单异常、密钥失效等Google Places API报错场景,捕获错误后可自定义执行隐藏下拉框、添加CSS类等逻辑:

方案1:监听谷歌API全局认证失败事件

谷歌地图服务遇到认证类错误(包含密钥无效、账单异常、权限未开通等场景)时,会主动触发window对象上的gm_authFailure事件,这是最直接的捕获方式,代码示例如下:

import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  // 你的组件原有配置
})
export class YourComponent implements OnInit, OnDestroy {
  // 标记Google API是否可用
  isGoogleApiValid = true;
  private authFailureHandler?: () => void;

  ngOnInit(): void {
    // 注册全局认证失败回调
    this.authFailureHandler = () => {
      this.isGoogleApiValid = false;
      // 这里执行你的自定义逻辑:隐藏下拉框、提示用户、降级处理等
      this.handlePlacesApiError();
    };
    (window as any).gm_authFailure = this.authFailureHandler;
  }

  private handlePlacesApiError(): void {
    // 示例:隐藏谷歌自动完成下拉容器
    const dropdownContainer = document.querySelector('.pac-container') as HTMLElement;
    if (dropdownContainer) {
      dropdownContainer.style.display = 'none';
      // 也可以添加你自定义的CSS类
      // dropdownContainer.classList.add('custom-hidden-class');
    }
  }

  ngOnDestroy(): void {
    // 组件销毁时清理监听,避免内存泄漏
    if (this.authFailureHandler) {
      delete (window as any).gm_authFailure;
    }
  }
}

方案2:拦截Places API请求状态(覆盖更全的错误场景)

如果需要捕获除认证外的其他错误(比如配额耗尽、请求参数非法等),可以拦截原生AutocompleteService的请求回调,判断返回状态码:

// 在ngOnInit中调用该初始化方法
private initPlacesRequestInterceptor(): void {
  const win = window as any;
  if (!win.google?.maps?.places) return;

  // 保存原生方法
  const originalGetPredictions = win.google.maps.places.AutocompleteService.prototype.getPlacePredictions;
  // 重写方法插入错误判断逻辑
  win.google.maps.places.AutocompleteService.prototype.getPlacePredictions = function (request: any, callback: any) {
    originalGetPredictions(request, (predictions: any, status: string) => {
      // 匹配你需要捕获的错误状态
      const errorStatusList = [
        'REQUEST_DENIED', // 对应密钥无效、账单异常、白名单不匹配等场景
        'OVER_QUERY_LIMIT', // 配额耗尽
        'INVALID_REQUEST', // 请求参数非法
        'ACCESS_NOT_CONFIGURED' // 服务未开通
      ];
      if (errorStatusList.includes(status)) {
        this.isGoogleApiValid = false;
        this.handlePlacesApiError();
      }
      // 执行原有回调逻辑不影响正常功能
      callback(predictions, status);
    });
  };
}

方案3:动态控制样式隐藏下拉框

结合上面的错误捕获逻辑,可以通过Angular的类绑定更优雅地控制下拉框展示:

<!-- 输入框模板部分 -->
<input 
  type="text" 
  [ngClass]="{'places-disabled': !isGoogleApiValid}"
  ngx-google-places-autocomplete 
  [options]="yourOptions"
  (onAddressChange)="handleAddressChange($event)"
/>
/* 对应样式,直接隐藏失效状态下的下拉框 */
.places-disabled + .pac-container {
  display: none !important;
}

两种捕获方案可以同时使用,覆盖所有异常场景,错误触发后可根据业务需求灵活执行自定义逻辑。

内容的提问来源于stack exchange,提问作者Brian Akumah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:48:02