8

I am trying to initialize JavaScript SDK to use Facebook Graph API eventually. But it keep saying that Cannot find name FB, not sure why. Here is what I did,

componentDidMount() {
    (window as any).fbAsyncInit = function() {
        FB.init({ // this FB errors out
            appId            : "my-app-id",
            autoLogAppEvents : true,
            xfbml            : true,
            version          : "v2.11"
        });
    };

    (function(d: any, s: any, id: any) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return; }
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
    }(document, "script", "facebook-jssdk"));
}

P.S. I am using TSLint, that is why I have all those typedef any

Hafiz Temuri
  • 3,882
  • 6
  • 41
  • 66
  • have you tried with "window.fbAsyncInit" instead, and without those weird TSLint additions in general? where does it say that it cannot find FB? somewhere else, or right at FB.init? – andyrandy Jan 29 '18 at 22:25
  • right at `FB.init`. No, I haven't tried without `TSLint`, because its pretty much useless to me if it doesn't work with `TSLint`. – Hafiz Temuri Jan 29 '18 at 22:42
  • do you have a test link for us? with the information at hand, we can only say that the js sdk is not getting loaded. which is exactly what the error message says. – andyrandy Jan 30 '18 at 08:27
  • `FB` is a global `window` object (`window.FB`) provided when https://connect.facebook.net/en_US/sdk.js is loaded. For tslint to know where this global FB namespace comes from you need to declare it in your respective lint rc or define an interface for it. – skilleo Oct 17 '18 at 21:09

1 Answers1

11

Install https://www.npmjs.com/package/@types/facebook-js-sdk and add facebook-js-sdk to types in your tsconfig.ts or tsconfig.app.json if you have nested applications when using Angular CLI.

Example tsconfig.app.json:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/app",
    "types": [
      "node",
      "gapi", // google
      "gapi.auth2", // google
      "facebook-js-sdk" // facebook
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175