9

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"
    ]
  }
 }
zhu chen
  • 215
  • 2
  • 11
  • Let me know if need to include module as well – zhu chen Feb 20 '18 at 19:48
  • DId you import gapi in your component? import * from 'gapi' ? – David Feb 20 '18 at 21:18
  • Or if you are really stuck and nothing works, you can add `declare var gapi : any;` in your component file – David Feb 20 '18 at 21:28
  • Tried both way. No good. I tried including it in the tsconfig.app.json now and it returns the following error for me now. ERROR in src/app/order/order.component.ts(70,23): error TS2339: Property 'analytics' does not exist on type 'typeof client'. – zhu chen Feb 21 '18 at 15:28
  • Thank you! the declare var gapi: any; method did remove the error(Made a typo earlier when I tried it and I tried again). I am able to deploy the project now. However, I am facing another issue now. My deployed project is not calling the gapi code I have above, thus, not getting any data from google analytics for my post to my report model. Please advise! – zhu chen Feb 21 '18 at 17:02
  • declaring gapi as any will not have any effect on your code's logic. It'll just let typescript compile the component without throwing an error. You need to debug to check if the api lib is correctly imported and called – David Feb 21 '18 at 17:05
  • Nevermind, I just need to allow access from my google analytics side. Thank you!!! – zhu chen Feb 21 '18 at 17:43

4 Answers4

9

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>
Harrison O
  • 1,119
  • 15
  • 20
8

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

declare var gapi : any;
zhu chen
  • 215
  • 2
  • 11
1

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"]
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I did already, but it still have this error when I run ng build --prod. So should I import it on my component? – zhu chen Feb 20 '18 at 17:37
  • try adding to your compiler options as above – Sajeetharan Feb 20 '18 at 17:42
  • 1
    Did that already too. Please see post for that as well. Thanks! – zhu chen Feb 20 '18 at 17:43
  • try adding both. gapi and gapi.auth – Sajeetharan Feb 20 '18 at 17:47
  • Tried that, but this time, the localhost fail to compile and with same errors. "types": ["gapi", "gapi.auth"], – zhu chen Feb 20 '18 at 17:50
  • Should I post my codes as well? If so, please let me know – zhu chen Feb 20 '18 at 17:51
  • Same as the ones that I posted – zhu chen Feb 20 '18 at 17:52
  • 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'. – zhu chen Feb 20 '18 at 17:52
  • consider setting "typeRoots": [ "../node_modules/@types" ], – Sajeetharan Feb 20 '18 at 18:01
  • If I put the following code in - import "gapi", I get the following error - Property 'analytics' does not exist on type 'typeof client'. – zhu chen Feb 20 '18 at 21:29
  • Tried including the types and typeRoots in tsconfig.app.json now and it returns the following error. ERROR in src/app/order/order.component.ts(70,23): error TS2339: Property 'analytics' does not exist on type 'typeof client'. – zhu chen Feb 21 '18 at 15:29
  • have you added to the index html? – Sajeetharan Feb 21 '18 at 16:18
  • I did. Receiving error TS2339: Property 'analytics' does not exist on type 'typeof client now. I placed the script under the app-root tag – zhu chen Feb 21 '18 at 16:29
  • Hi, I used the declare var gapi: any; method and it removed the error. I am able to deploy the project now. However, I am facing another issue now. My deployed project is not calling the gapi code I have above, thus, not getting any data from google analytics for my post to my report model. Please advise! – zhu chen Feb 21 '18 at 17:03
1

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.

Severin Jaeschke
  • 661
  • 7
  • 22