简体   繁体   中英

Global function not visible inside function

I am injecting google analytics code via a file named analytics.js inside webpage header like this:

<script src="/assets/js/analytics.js"></script>

This works fine. If I go to webpage, I have access to global function ga from my console.

However, in my service, which looks like that:

import {Injectable} from "@angular/core";
import {Router, NavigationEnd} from "@angular/router";
var ga:any;

@Injectable()
export class GoogleAnalyticsService{
    constructor(){
      console.log(ga);
    }

    test(){
        console.log(typeof ga);
    }
}

In both cases, console output is undefined. I inject my Angular2 at the bottom of html code, so it is loaded as last script.

What is going on?

Replace:

var ga:any;

with

declare var ga: any;

First one creates new variable while last one declares type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM