Angular 2+错误:找不到名字'gapi'

时间:2018-02-20 17:34:22

标签: angular google-analytics-api

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

这就是我在角度应用中的称呼方式    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"
    ]
  }
 }

4 个答案:

答案 0 :(得分:1)

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

declare var gapi : any;

答案 1 :(得分:0)

要在Angular中使用gapi a,请使用NPM安装类型脚本定义。

npm install --save @types/gapi

还尝试添加到您的compilerOptions:

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

答案 2 :(得分:0)

如果要使用类型定义的解决方案,请查看Jack的answer

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

通过将reference path直接提供给具有类型描述的文件来实现。 (摘自上面链接文章中杰克的回答)

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

或使用reference types引用@types包

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

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

答案 3 :(得分:0)

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

安装以下内容。

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

tsconfig.json部分的tsconfig.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>