Search code examples
angulartypescriptgoogle-api-js-client

ReferenceError: gapi is not defined, but I tried everything


This might sound like a dumb question because there are tons of questions of the exact same problem, but none of them could nearly help. I am using angular and in the ngAfterViewInit() I have following code: gapi.load("auth2", () => console.log("test"). I have installed @types/gapi and @types/gapi.auth2 via npm. In my tsconfig.app.json I have included "gapi" and "gapi.auth2" in the types in compilerOptions. Also in the component's html fiel I put <script src="https://apis.google.com/js/api.js"></script> in the head. I already tried to write declare var gapi: any; to the imports, but it didn't work either. Also I tried the triple slas directive /// <reference path="../../../node_modules/@types/gapi/index.d.ts"> or /// <reference types="gapi">, but none of them worked. I have no clue what to do because I tried everything that I could find in hours of research. Thanks in advance :)


Solution

  • Try using a dynamic import:

    import("https://apis.google.com/js/api.js").then(() => {
      gapi.load("client:auth2", () => {console.log("success")});
    });