Angular 2+ Error: Cannot find name 'gapi'

你离开我真会死。 提交于 2019-12-10 19:41:44

问题


Basically, I am receiving the error below when I call the google analytics api for core reporting data. It works on my localhost server but when I try to deploy the app, it fails for me. Please advise on how to import the "gapi" variable in angular2+. Many thanks!

This is how I call it in my angular app.
gapi.auth.authorize(authData, (res:any)=>{})

ERROR in src/app/order/order.component.ts(65,7): error TS2304: Cannot find name 'gapi'. src/app/order/order.component.ts(66,11): error TS2304: Cannot find name 'gapi'. src/app/order/order.component.ts(67,11): error TS2304: Cannot find name 'gapi'. src/app/order/order.component.ts(69,13): error TS2304: Cannot find name 'gapi'. src/app/order/order.component.ts(71,15): error TS2304: Cannot find name 'gapi'. src/app/order/order.component.ts(77,17): error TS2304: Cannot find name 'gapi'.

Below are my codes

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"
    ]
  }
 }

回答1:


Added the following code to the component and allowed access from Google Analytics for deploy link. Thank you all!

declare var gapi : any;



回答2:


To use gapi a with Angular, install the type script definitions using NPM.

npm install --save @types/gapi

also try adding to your compilerOptions:

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



回答3:


If you want a solution with type definitions have a look at this answer from Jack:

The part you and I were missing is the tripe-slash-directive telling the compiler where it needs to look up the gapi type information.

Either do this by providing the reference path directly to the file with the type description. (From Jack's answer in the linked post above)

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

Or use reference types to reference an @types package

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

You will have to add this reference to every ts file that contains a reference to gapi.




回答4:


For those who maybe having similar issues, the use of NgZone will solve the problem, follow these steps:

Install the following.

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

In tsconfig.json or tsconfig.app.json within compilerOptions section add this "gapi", "gapi.auth2" to types. It will look like

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

Then in you service or component, use NgZone, you import it from @angular/core

Here is example:

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 documentation... read more

In index.html, depending what you want, you may need to add the following within the <head></head> tag

<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>


来源:https://stackoverflow.com/questions/48891097/angular-2-error-cannot-find-name-gapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!