Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button's data-onlogin attribute.

Even though I have defined a typescript function within the same component as the login button, it seems that the button is not recognizing it.

Additionally, I am utilizing facebook-js-sdk type definitions.

login.component.html

<div 
  class="fb-login-button" 
  data-width="" 
  data-size="large" 
  data-button-type="login_with" 
  data-auto-logout-link="false"
  sdata-use-continue-as="false"
  data-onLogin="checkLoginStatus()"
>
</div>

login.component.ts

import { Component, OnInit } from '@angular/core';

// Defining the Facebook Javascript SDK
declare var FB: any;

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    constructor() { }

    ngOnInit() {

    }

    checkLoginStatus() {
        FB.checkLoginStatus((result) => {
            console.log(result);
        });
    }
}

index.html

<body>
    <script>
        window.fbAsyncInit = function () {
            FB.init({
                appId: '{app-id}',
                autoLogAppEvents: true,
                xfbml: true,
                version: 'v3.3'
            });
        };
    </script>

    <script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>

    <app-root></app-root>

</body>

An error is being thrown by ZoneJS in the console stating:

Uncaught ReferenceError: checkLoginStatus is not defined

Answer №1

In order for the FB plugin to be accessible, the method must be aliased on the window object, as shown below:

ngOnInit() {
   window['checkLoginStatus'] = this.checkLoginStatus.bind(this);
}

checkLoginStatus(){
....
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transformed Vue code with TypeScript using a more aesthetically pleasing format, incorporating ref<number>(0)

Original Format: const activeIndex = ref<number>(0) Formatted Version: const activeIndex = ref < number > 0 Prettier Output: click here for image description Prettier Configuration: { "$schema": "https://json.schemastore.org ...

What is the best method for translating object key names into clearer and easier to understand labels?

My backend server is sending back data in this format: { firstName: "Joe", lastName: "Smith", phoneNum: "212-222-2222" } I'm looking to display this information in the frontend (using Angular 2+) with *ngFor, but I want to customize the key ...

A guide on transforming a string into an array of objects using Node.js

Hey everyone, I have a single string that I need to convert into an array of objects in Node.js. let result = ""[{'path': '/home/media/fileyear.jpg', 'vectors': [0.1234, 0.457, 0.234]}, {'path': '/home/med ...

Converting city/country combinations to timezones using Node.js: A comprehensive guide

When provided with the name of a city and country, what is the most reliable method for determining its timezone? ...

What is the best way to mix up the images in my memory game?

My JavaScript memory game is functioning properly, but I would like the images to load in a random order. Unfortunately, I'm not sure how to accomplish this. Here is the current setup: var easyImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", " ...

Ways to address the Generic Object Injection Sink eslint error (security/detect-object-injection)

I am seeking a solution to resolve this issue without needing to deactivate eslint. Moreover, I am eager to comprehend the cause of the error. const getMappedCard = (cardName: CardName) => { const mappedCards = { Mastercard: <Mastercard /> ...

Learn how to implement icons within Textfield components using Material-UI and TypeScript in React

I have successfully created a form with validation using TypeScript Material UI and Formik. Now, I am looking to enhance the visual appeal by adding a material UI Icon within the textfield area. Below is a snippet of my code: import React from 'reac ...

The Google Maps API swipe feature on mobile devices is causing issues with screen scrolling

When users visit my website on mobile, they encounter a situation where Google Maps suddenly covers the entire page, preventing them from scrolling away. This is because swiping up or down only moves the map view within Google Maps, instead of scrolling th ...

Error message: Angular encountered a SyntaxError when parsing JSON data due to an unexpected character at the beginning of the data

Encountering SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data After validating the JSON, it was discovered that the error lies in: let json = JSON.stringify(user); let params = "json="+json; // The error se ...

JavaScript date input formatting with HTML

When using the input date picker in HTML, the default format displayed is MM-DD-YYYY. <input type="date" id="gdatum" /> Is there any method to change the mask to DD-MM-YYYY? ...

The length function appears to be signaling an unanticipated error

Recently, I encountered an issue with the code execution. Although the code appears to be functioning correctly, it is throwing an uncaught error. Is there a reason for concern regarding this situation? var xmlhttp = new XMLHttpRequest(); xmlhttp.onread ...

Problem with Marionette AppRouter compatibility when used with Browserify

app.js module.exports = function () { if (!window.__medicineManager) { var Backbone = require('backbone'); var Marionette = require('backbone.marionette'); var MedicineManager = new Marionette.Application(); Medicin ...

Is there a way to view the text as I enter it while drawing text on an image canvas?

I currently have a canvas setup that allows users to upload an image and display it on the canvas. Users can then input text to be drawn on the image by clicking the submit button. However, I would like the entered text to appear on the image as it is bein ...

Ways to properly link a webpage using the anchor tag's href attribute

I am currently working with reactjs and bootstrap, and I am trying to display and collapse an unordered list within a list item (nested unordered list). Bootstrap provides a useful collapse feature for this purpose. By using an anchor tag with a data-toggl ...

The useTransition() method in React remains stuck in the isPending state when making API calls from routes in the /pages/api directory

I'm encountering an issue with the useTransition() function where it remains true and never changes back to false. I am attempting to delete a record from MongoDB and after completion, I want to refresh the React Server Component following the guideli ...

Declaring a function type with a void parameter type in typescript

Embarking on my journey with ts and currently exploring TypeGraphQL. I came across something that caught my attention and seems unfamiliar to me: export declare type ReturnTypeFunc = (returns?: void) => ReturnTypeFuncValue; How should this type be unde ...

vue implementing autoscroll for long lists

I am looking to implement an autoscrolling log feature on my webpage that is dynamically fetched from a REST endpoint. To handle the potentially large size of this log, I decided to use vue-virtual-scroll-list. Additionally, I wanted the log to automatical ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...

Is the callback for a request always invoked?

When using the npm module request, I often encounter situations where some requests are not called back, leading to various issues. This has raised a question in my mind - is it expected for the request function to always callback? For instance, if my req ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...