Logging into Facebook using Angular 2

As I work on developing a website that requires users to log in with their Facebook account, I am facing some challenges. I am utilizing Angular 2 and TypeScript for this project, but the user information retrieval is not working as expected.

Let's delve into the code:

import {Component} from 'angular2/core';
import {Main} from './pages/main/main';

declare const FB: any;

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.html',
  directives: [Main]
})

export class AppComponent implements OnInit { 

token: any;
loged: boolean = false;
user = { name: 'Hello' };

constructor() { }

statusChangeCallback(response: any) {
    if (response.status === 'connected') {
        console.log('connected');
    } else {
        this.login();
    }
}

login() {
    FB.login(function(result) {
        this.loged = true;
        this.token = result;
    }, { scope: 'user_friends' });
}

me() {
    FB.api('/me?fields=id,name,first_name,gender,picture.width(150).height(150),age_range,friends',
        function(result) {
            if (result && !result.error) {
                this.user = result;
                console.log(this.user);
            } else {
                console.log(result.error);
            }
        });
}

ngOnInit() {
    FB.getLoginStatus(response => {
        this.statusChangeCallback(response);
    });
}
}

Essentially, when the page loads, it checks if the user is logged in via Facebook. If not, the login method is invoked. The me method fetches user information such as name and first name. Upon successful login, the browser console displays details like:

Object {id: "666", name: "Paulo Henrique Tokarski Glinski", first_name: "Paulo", gender: "male", picture: Object…}

All seems well! However, I aim to take that object and assign it to a User object. Here's what I have in mind:

me method:

this.user = result;    
console.log(this.user);

Unfortunately, the user data only remains within the method scope. When attempting to access it outside, no values are returned. In my previous experience with AngularJS, a similar approach yielded successful results.

If anyone could provide guidance or assistance, it would be greatly appreciated!

Answer №1

To maintain the same context, fat arrow functions can be utilized...

authenticate() {
  FB.login((response: any) => {
    this.isLoggedIn = true;
    this.token = response;
  }, { scope: 'user_friends' });
}

Answer №2

To integrate the Facebook JavaScript SDK into your website, simply insert the following code snippet in your index.html file:

<script src="//connect.facebook.net/en_US/sdk.js"></script>

Next, within the ngOnInit() method of your component, add the following initialization code:

    `FB.init({
        appId      : 'your-app-id',
        cookie     : false, 
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });`

Answer №3

Implementing Angular 2 Service at a High Level

import {Injectable} from '@angular/core';
import { Location } from '@angular/common';
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { ConfigService } from "app/core/services/config.service";

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch';

@Injectable()
export class AuthService {

   constructor(private http: Http,
               private configProvider:ConfigService) {
    }
    authenticateFacebook(){
         window.location.href = 'https://www.facebook.com/v2.9/dialog/oauth?client_id='+
         this.configProvider.config.facebook.clientId + 
         '&redirect_uri='+ this.configProvider.config.facebook.redirectURI + '&scope=public_profile';
    }
    getAccessToken(authenticationCode: string){
        var authProviderUrl = 'https://graph.facebook.com/v2.9/oauth/access_token';
        var authParameters = {
            client_id: this.configProvider.config.facebook.clientId,
            redirect_uri: this.configProvider.config.facebook.redirectURI,
            client_secret: this.configProvider.config.facebook.clientSecret,
            code: authenticationCode
        };
        var params = [];
        for (var k in authParameters) {
            params.push(k + '=' + authParameters[k]);
        }
        var authOpenURI = authProviderUrl + '?' + params.join('&');

         return this.http.get(authOpenURI)
                   .map(res => res.json())
                   .catch(err => Observable.throw(err));
    }
    getUserFacebookProfile(accessToken:string):Observable<any>{
        var fields = ['id', 'email', 'first_name', 'last_name', 'link', 'name','picture.type(small)'];
        var graphApiUrl = 'https://graph.facebook.com/v2.5/me?fields=' + fields.join(',');

        return this.http.get(graphApiUrl+'&access_token='+accessToken+'')
                   .map(res => res.json())
                   .catch(err => Observable.throw(err)); 
    }

Function called at the main level, to be located in the component of your redirect URI

//Perform Facebook authentication check
    if (window.location.href.indexOf("code") > -1){
      var code = window.location.href.substring(window.location.href.indexOf("?") + 1).split('&')[0].split('=')[1];
      this.retrieveFaceBookProfile(code);
    }
    //Retrieve profile from facebook
    retrieveFaceBookProfile(code:string){
      this.authService.getAccessToken(code).subscribe(oathAccessData => {
        this.authService.getUserFacebookProfile(oathAccessData.access_token).subscribe(profile => {
           this.userProfile = new UserProfile(profile.name,profile.email, profile.picture.data.url,"facebook",
           profile.id);},err => { console.log(err); });},err => { console.log(err);});

                  this.router.navigate(['/dashboard']);     
    }

Answer №4

This instance is full of enchantment. Would it be beneficial to store the current object's this in a variable and utilize that in the callbacks (thus avoiding concern over what their this might be)?

For example:

login() {
    var self = this;
    FB.login(function(result) {
        self.logged = true;
        self.token = result;
    }, { scope: 'user_friends' });
}

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

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

What is preventing the function from successfully compiling text from various files that are uploaded using the HTML5 file reader into an array?

My current challenge involves attempting to upload two text files using the HTML 5 file reader. While I can successfully get the files into an array, encountering difficulty arises when trying to return that array from the function. One solution could be ...

Strict mode error occurs when attempting to assign a value to ngComponentOutlet that is incompatible with the type of the lazy-loaded component

I am attempting to implement lazy loading for a component in Angular 11 (strict mode) using guidance from this tutorial. Dealing with strict mode has been challenging as there are very few resources available that cater to it. The goal is to have a compon ...

Utilize the power of XMLHttpRequest to fetch and load numerous audio files, seamlessly integrating them for playback through the Web Audio

I am looking to create a web application that loads three different audio files, each one second long, in a specific order, and then merges them into a single Audio Buffer consecutively. To illustrate my goal, here is a sample code snippet: var AudioCo ...

How to retrieve client's hostname using Node and Express

How can the client's hostname be retrieved in a Node / Express server? Is there a method similar to req.connection.remoteAddress that can be used to obtain the client's hostname? ...

Why does Laravel DatePicker consistently default to showing the previous month instead of the selected month?

I've hit a roadblock trying to pinpoint the source of this error in the Tailwind UI Datepicker. Whenever I choose 09-08-2021 on the visual Datepicker, the value ends up saving as 09-07-2021. I've researched similar cases where the month value re ...

Implementing Angular 2 reactive forms checkbox validation in an Ionic application

I have implemented Angular Forms to create a basic form with fields for email, password, and a checkbox for Terms&Conditions in my Ionic application. Here is the HTML code: <form [formGroup]="registerForm" (ngSubmit)="register()" class="center"> ...

Exporting keys of objects one by one

I am trying to mock the `fs` module in vitest using [memfs](https://github.com/streamich/memfs). To do this, I have created a mock file located at `./__mocks__/fs.ts` where I have set up the mocked volume and fs. However, I am facing an issue with the moc ...

Load the scripts only if they have not already been loaded, and proceed to utilize them

Currently, I have a situation where I must load 4 javascript libraries if they have not been loaded already, and then proceed to utilize their functions. However, I am encountering an issue with Uncaught ReferenceError: sbjs is not defined. Even though th ...

Creating a Docker image for an Angular application with Node.js

Currently, I am attempting to develop an Angular application within a Docker environment and then run it as a container locally using Node.js. I have utilized the following Dockerfile to build the image, however, I am unsure of what might be missing when ...

Error: React.js encountering an issue where property 'map' is undefined and cannot be read

While following an online tutorial for React.js on controlled inputs, I am continuously encountering the error: TypeError: Cannot read property 'map' of undefined import CallRow from "./CallRow"; import React from "react"; class SearchPage ...

What could be causing the queuing of multiple Ajax requests in ExtJS?

I am encountering an issue with my grid setup. I have a menu on the left side for each item on the grid, and this menu's items change based on the selection in the grid. When the event selection is triggered, an Ajax.request function is called to hand ...

Ionic4: Troubleshooting the playback of audio files on a web-based application

Currently, my project involves using Ionic 4 in combination with Angular. I am facing a challenge where I need to play an audio file (mp3/wav) when an image is clicked. Despite working on this for a week, I have been unable to figure it out. Can anyone pr ...

What is the best way to retrieve the value of this event in a React component?

Is there a way to retrieve the value of an input field? Typically, I would use event.target.value to do so. However, in this case, that method is not viable because the path of event.target leads me to an li element instead: https://i.sstatic.net/0iB9v.pn ...

Access mat-sidenav from the right side with a minimized icon style

I am currently using angular 7 along with angular material components. Recently, I attempted to configure the <mat-sidenav> with a Mini icon variant positioned at end. My goal is for all icons to remain in their designated positions when the side nav ...

The custom component I created seems to be unaffected by the inline styles in React

Having an issue with a custom component where I am trying to add margin-top in one of my uses. I attempted using <MyComponent style={{ marginTop: '10px' }}> and also const myStyle = { marginTop: '10px' }; `<MyComponent style= ...

Can you identify the specific syntax for a 'set' function in TypeScript?

I have a TypeScript function that looks like this: set parameter(value: string) { this._paremeter = value; } It works perfectly fine. For the sake of completeness, I tried to add a type that specifies this function does not return anything. I experimen ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Automatic login using Selenium Webdriver

I am currently using Selenium WebDriver with C# to automate the process of logging in and posting a random message on Facebook, LinkedIn, and Twitter. However, I'm facing difficulties clicking the post button on both LinkedIn and Facebook. Any assista ...

Enhance the functionality of angular-material buttons by incorporating dynamic loading animations into

I am currently working on a solution in Angular 12 to disable a button (and show a spinner) when it is clicked, until the API responds. To achieve this, I plan to follow a similar approach to the angular-material button implementation. Essentially, I want ...