Angular 2+ Error: Cannot find name 'gapi'

Angular 2+ Error: Cannot find name 'gapi'

基本上,当我为核心报告数据调用 google 分析 api 时收到以下错误。它可以在我的本地主机服务器上运行,但是当我尝试部署该应用程序时,它对我来说失败了。请告知如何在 angular2+ 中导入 "gapi" 变量。非常感谢!

这就是我在 angular 应用程序中的调用方式。
gapi.auth.authorize(authData, (res:any)=>{})

src/app/order/order.component.ts(65,7) 中的错误:错误 TS2304:无法 查找名称 'gapi'。 src/app/order/order.component.ts(66,11):错误 TS2304:找不到 姓名 'gapi'。 src/app/order/order.component.ts(67,11):错误 TS2304:找不到 姓名 'gapi'。 src/app/order/order.component.ts(69,13):错误 TS2304:找不到 姓名 'gapi'。 src/app/order/order.component.ts(71,15):错误 TS2304:找不到 姓名 'gapi'。 src/app/order/order.component.ts(77,17):错误 TS2304:找不到 姓名 'gapi'.

下面是我的代码

gapi.auth.authorize(authData, (res:any)=>{
      gapi.client.load('analytics', 'v3').then(function() {
      gapi.client.analytics.management.accounts.list().then( (accountResponse:any) =>{
        let accountId = accountResponse.result.items[4].id;
        gapi.client.analytics.management.webproperties.list({'accountId': accountId})
        .then((accountPropertiesResponse:any) => {
          gapi.client.analytics.management.profiles.list({
              'accountId': accountPropertiesResponse.result.items[0].accountId,
              'webPropertyId': accountPropertiesResponse.result.items[0].id,
          })
          .then((profileIdResponse:any)=>{

            gapi.client.analytics.data.ga.get({
              'ids': 'ga:' + profileIdResponse.result.items[0].id,
              'start-date': sevenDaysAgo,
              'end-date': databaseDate,
              'metrics': 'ga:sessions',
              'dimensions': 'ga:deviceCategory',
            }).then((coreReportResponse:any)=>{
              mobileNum = coreReportResponse.result.rows[1][1];
              desktopNum = coreReportResponse.result.rows[0][1];
              tabletNum = coreReportResponse.result.rows[2][1];
              visits = coreReportResponse.result.totalsForAllResults['ga:sessions'];
            });
          });
        });
      });
    });
  });

index.html

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>ShopifyReport</title>
 <base href="/">

 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="icon" type="image/x-icon" href="favicon.ico">
 </head>
<body>
 <app-root></app-root>
 <script src="https://apis.google.com/js/client.js?onload=authorize" 
async defer></script>

  </body>
      </html>

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types",
    ],
    "types": ["gapi", "gapi.auth2", "gapi.auth"],
     "lib": [
      "es2017",
      "dom"
    ]
  }
 }

要将 gapi a 与 Angular 一起使用,请使用 NPM 安装类型脚本定义。

npm install --save @types/gapi

也尝试添加到您的编译器选项:

"compilerOptions": {
     "types": ["gapi"]
}

向组件添加了以下代码并允许从 Google Analytics 访问以部署 link。谢谢大家!

declare var gapi : any;

如果您想要一个带有类型定义的解决方案,请查看来自 Jack 的answer

你和我缺少的部分是 tripe-slash-directive 告诉编译器它需要在哪里查找 gapi 类型信息。

要么通过将 reference path 直接提供给具有类型描述的文件来执行此操作。 (来自杰克在上面链接 post 中的回答)

// You may not have this explicit reference.
/// <reference path="../../node_modules/@types/gapi/index.d.ts" />

或使用reference types引用@types包

/// <reference types="gapi" />

您必须将此引用添加到每个包含对 gapi 的引用的 ts 文件。

对于那些可能有类似问题的人,使用NgZone将解决问题,请按照以下步骤操作:

安装以下内容。

npm install --save @types/gapi
npm install --save @types/gapi.auth2

tsconfig.jsontsconfig.app.jsoncompilerOptions 部分中,将此 "gapi", "gapi.auth2" 添加到 types。它看起来像

"types": ["gapi", "gapi.auth2"],

然后在您的服务或组件中,使用 NgZone,您从 @angular/core

导入它

示例如下:

import { Component, NgZone, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-google-app',
  templateUrl: './google-app.component.html',
  styleUrls: ['./google-app.component.scss']
})
export class GoogleAppComponent implements OnInit, AfterViewInit {

constructor(private ngZone: NgZone) { }

ngAfterViewInit() {
    this.ngZone.run(() => {
        // example to render login button
        gapi.signin2.render('my-signin2', {
        ...
        ...
        });

        // example to load client
        gapi.load('client', {
         ...
         ...
        });

    });
  }    
}

Angular NgZone 文档...read more

index.html中,根据需要,您可能需要在<head></head>标签

中添加以下内容
<meta name="google-signin-client_id" content="xxxxxxxxxx.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
<script src="https://apis.google.com/js/api.js"></script>