Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global variable in Angular 2 Component

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;
        });
    }

};
like image 746
Shan Khan Avatar asked Dec 18 '22 18:12

Shan Khan


1 Answers

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

like image 94
basarat Avatar answered Dec 26 '22 15:12

basarat