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

Allow Visual Studio Code to create a constructor for Typescript class

When developing Angular 2 apps in Typescript using Visual Studio Code, one common task is writing constructors with their parameter list. Is there a way to save time and effort on this? It would be really helpful if the IDE could automatically generate th ...

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

Clickable element to change the display length of various lists

I am working on a project where I have lists of checkboxes as filters. Some of these lists are quite long, so I want to be able to toggle them to either a specified length or the full length for better user experience. I have implemented a solution, but th ...

Encountering 404 Errors while Attempting to Reach API Endpoint in an Express.js Application Hosted on cPanel

I have a Node.js application running on cPanel, and I'm facing 404 errors when trying to access an API endpoint within my app. Let me provide you with the setup details: Directory Structure: public_html/ server.mjs index.html node_modules ...

Crafting an interactive saturation effect for mouseover interactions in a circular design

I'm looking to create a unique hover effect for my images. I have both a desaturated version and a full color version of the same image. My idea is to have mousing over the desaturated image reveal a circle spotlighting the color version underneath, a ...

The concept of setTimeout and how it affects binding in JavaScript

I have limited experience with jquery, mainly using it for toggling classes. However, I will do my best to explain my issue clearly. I have three div elements and when one is clicked, the other two should rotate 90 degrees and then collapse to a height of ...

Transferring Data between Rails and Angularjs using JSON

Utilizing Angularjs to fetch JSON data from a Rails test app deployed on Heroku is proving to be a bit challenging. Below you can find the snippets of my Angular and Rails code. An error message displayed in my Firebug console reads: "NetworkError: 404 N ...

What is the best way to ensure that an iframe adjusts its height to fit the content within a tabbed container?

Is there a way to dynamically set the height of an iframe to match the content inside it when clicking on a tabbed plane? Initially, I used a fixed height of 1000px. How can this be achieved? <div class="container-fluid text-center"> <div ...

Trouble with the Ngx-Captcha feature

I am currently utilizing https://www.npmjs.com/package/ngx-captcha/v/11.0.0. <ngx-recaptcha2 #captchaElem [siteKey]="'6Leh1ZIjAAAAAG8g0BuncTRT-VMjh3Y7HblZ9XSZ'" (success)="handleSuccess($event)" [useGlobalDomain]="fals ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

Tips on how to effectively simulate a custom asynchronous React hook that incorporates the useRef() function in jest and react-testing-library for retrieving result.current in a Typescript

I am looking for guidance on testing a custom hook that includes a reference and how to effectively mock the useRef() function. Can anyone provide insight on this? const useCustomHook = ( ref: () => React.RefObject<Iref> ): { initializedRef: ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...

Tips for retrying an insertion into the database when a duplicate unique value is already present

After thorough searching, I couldn't find any existing patterns. My goal is to store a unique key value in my MySQL database. I generate it on the server side using this code: var pc = require('password-creator'); var key = pc.create(20); ...

Tips for effectively changing Observable data into an Array

I am currently attempting to transform an Observable into an Array in order to loop through the Array in HTML using ngFor. The Typescript code I have now is causing some issues. When I check the testArray Array in the console, it shows up as undefined. it ...

Returning data to be displayed in Jade templates, leveraging Express and Node.js

Yesterday, I had a question. Instead of using next() and passing an Error object, I decided to figure out what it was doing and replicate it. So now, when someone logs in and it fails, I handle it like this: res.render("pages/home", { ...

Angular2 fills up the table with data for a particular row

I have a specific requirement where I need to display only some columns of a table within a div. When I click on 'See' for a particular row, I want to reveal the remaining columns of that table (currently it reveals all rows by default). https:/ ...

The issue with MVC4 and Ajax requests for converting image ByteArrays appears to be problematic

I am attempting to change an image in my View with a click event. However, when the controller returns a byte array, the original image is replaced with an empty one. Below is the code from my Controller: [HttpPost] public byte[] GetSelectedI ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

Undefined property encountered while trying to set a property during the invocation of a template

I am currently working on creating a dynamic popup using Bootstrap where I want to add a header, body, and footer dynamically to an HTML template for a modal. However, when I run the code, I encounter errors in the browser console because the values for th ...