How to access global variable in Angular 2 Component

11,134

Solution 1

You have in your code :

    var gapi: any;
    console.log(gapi); // undefined

The line var gapi creates a new local variable at runtime. You don't want to create a local variable. You want to declare that one exists globally. Create a globals.d.ts file and add the following to it:

declare var gapi:any;

More

JavaScript to TypeScript Migration guide : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html

Solution 2

You can easily access global variables by referencing window, like so

gapi = window["gapi"];

or

let gapi = window["gapi"];
Share:
11,134
Shan Khan
Author by

Shan Khan

Masters in Machine Learning, currently working in Data Scientist and Experience of more than 7 years in IT dealing with wide range of applications and platforms, experience within multi-tier environments, analysis, design, consultation and teams leading roles. Delivered/ deployed mission critical applications/ solutions for worldwide customers on highly availability productions environments. Expertise: ➢ Machine Learning and Natural Language Processing ➢ Implementing DevOps process inside Team ➢ Micro services and Azure App Service ➢ Worked in Dynamics 365 Integration Product Development ➢ Worked in SAP HCM Module Product Development ➢ System Analysis and Design More Details on my resume available @ Developer Story

Updated on June 10, 2022

Comments

  • Shan Khan
    Shan Khan almost 2 years

    I want to access google api library from angular 2 module in typescript. How to do that. When i try to access (gapi) i get the undefined. is there any NPM module that work as typescript library in angular 2 to which i can use or i have to use the js file.

    Following is the module code and library reference:

     <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
    

    .

        @Component({
    
        selector: "main-app",
        template: "{{title}}",
        providers: [HTTP_PROVIDERS, AuthService]
    
    })
    export class AppComponent implements OnInit {
        public title: string = '';
        constructor(private _authService: AuthService) {
            var gapi: any;
            console.log(gapi); // undefined
        }
        ngOnInit() {
    
            this._authService.getAuthSettings().subscribe((set: AppSetting) => {
                this.title = set.Scopes;
            });
        }
    
    };