Utilizing Firebase login to integrate with Facebook API

My current setup involves Facebook authentication tied to login, all managed through Firebase. However, I now face the need to make an API call to Facebook using 'me/friends/' endpoint without having to send another request since I am already logged in.

To facilitate my connection to Facebook within Angular, I am utilizing the following wrapper: https://github.com/ccoenraets/OpenFB

Answer №1

No need for a wrapper. Utilize $firebaseAuth() along with $http() for seamless Graph API requests.

The Graph API is user-friendly and integrates smoothly with Firebase.

Ensure that you have granted the Facebook Friends permission; otherwise, you will not receive any data in return.

You can employ $firebaseAuth() to log in and acquire the Facebook access_token. This token can then be utilized with the Graph API for retrieving data via HTTP requests, which Angular simplifies through its $http library.

My coding style may differ, as I prefer following the guidelines of the Angular styleguide.

angular.module('app', ['firebase'])
  .constant('FirebaseUrl', 'https://<my-firebase-app>.firebaseio.com/')
  .constant('FacebookAppId', '<app-id>')
  .service('RootRef', ['FirebaseUrl', Firebase])
  .factory('Auth', Auth)
  .factory('Friends', Friends)
  .controller('MainCtrl', MainCtrl);

function Friends($http, RootRef, $q, FacebookAppId) {

  function getFriends() {
    // Retrieve the currently logged-in user (could be null)
    var user = RootRef.getAuth();
    var deferred = $q.defer();
    var token = null;
    var endpoint = "https://graph.facebook.com/me/friends?access_token="

    // If no user is logged in, reject with an error and return the promise
    if (!user) {
      deferred.reject('error');
      return deferred.promise;
    } else {
      // User is present, retrieve the token
      token = user.facebook.accessToken;
      // Append the token to the endpoint
      endpoint = endpoint + token;
    }

    // Initiate the HTTP call
    $http.get(endpoint)
      .then(function(data) {
        deferred.resolve(data);
      })
      .catch(function(error) {
        deferred.reject(error);
      });

    // Return the promise
    return deferred.promise;
  }

  return {
    get: getFriends
  };
}
Friends.$inject = ['$http', 'RootRef', '$q', 'FacebookAppId'];

function Auth($firebaseAuth, RootRef) {
  return $firebaseAuth(RootRef);
}
Auth.$inject = ['FirebaseAuth', 'RootRef'];

function MainCtrl($scope, Friends) {

  $scope.login = function login() {
    Auth.$authWithOAuthPopup('facebook').then(function(authData) {
      console.log(authData, 'logged in!');
    });
  };

  $scope.getFriends = function getFriends() {
    Friends.get()
      .then(function(result) {
        console.log(result.data);
      });
  };

}
MainCtrl.$inject = ['$scope', '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

The visual representation of my data in Highchart appears sporadic, with the points scattered rather than following a clean, linear progression from left to right

I am working on displaying a 2D array [timestamp, count] on a highchart for the past 90 days from left to right. However, I am facing an issue where the chart appears sporadic when introduced to production data. It works fine with smaller datasets. After ...

The C# method is receiving a null array through Ajax

When I retrieve an array in a loop and pass it through an ajax call to my C# method, I'm encountering a problem where only null values are being received in my parameter. The count of the array is coming through, but the actual data seems to be lost. ...

Issue encountered when trying to import @tensorflow/tfjs-node in conjunction with the face-api.js library within a node.js environment

Using the @tensorflow/tfjs-node package along with face-api.js to enhance performance, here is my code snippet: // Import nodejs bindings to native tensorflow, // Not required but will significantly speed up operations (Python required) require('@tens ...

JSON string inside a string-type in AWS model

My goal is to create a basic model that can accept a JSON string instead of defining all variables/elements upfront. The model will have an "options" element which will hold a JSON string. Below is the structure of my model. { "$schema": "http://json-sch ...

Encountering an unusual error while utilizing the Rails 3 form_for with the :remote option set to true

Encountering an error and seeking assistance: try { Element.update("status", "There seems to be an issue with this product."); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.update(\"status\", &bsol ...

Is there a way to retrieve an audio file using npm request in a Node.js environment?

I'm dealing with a piece of code that retrieves raw data for me requestPromisePost(options) { return new Promise((resolve, reject) => { request(options, function (error, response,dfdf) { if (error) return ...

Exploring the features of React.js version 16

I'm confused about what {...props} does. I know it makes passing props easier, but what happens if there are no props to begin with? Take this example: const input = (props) => { let inputElement = null; switch(props.inputtype) { ...

Issue with Angular JS: ng-model does not update when input value is changed using jQuery

As a newcomer to AngularJS, I am currently working on creating a directive that consists of a list of input fields. The goal is for the "done" function to be triggered when the comma key (which corresponds to the number 188 in the plunker) is pressed, resu ...

What is the best method to deactivate zoom in/out buttons using JavaScript?

As a newcomer to Phonegap, I've managed to implement zoom in/out functionality using websettings in the .java file. However, I now face a challenge where I need to disable/enable the zoom in/out buttons and stop scrolling at a specific point. I attemp ...

What is the best way to access the primitive value of an attribute directive in

I'm having trouble retrieving the actual value of a directive attribute. Instead of getting the raw value, I keep getting the literal attribute name. --HTML <input my-directive="5==5" /> <div my-directive="isFoodReady()"> <!--some c ...

Clicking the mouse within three.js

I'm facing an issue with my webpage that features a three.js (webgl) graphic created using a .dae file imported from Blender. My goal is to draw a square or mark wherever the mouse is clicked, but for some reason, the square appears in a different loc ...

What causes the conflict between Nodejs usb module and Electron?

Apologies for the lengthy post, but I've been tirelessly searching for a solution online without any luck. My goal is to create a basic Electron application that can display an HTML page (which is working fine) and control a printer through the USB mo ...

Remove elements from an array based on the indices provided in a separate array

1) Define the array a = [a,b,c,d,e,f,g,h,i,j]; using JavaScript. 2) Input an array 'b' containing 5 numbers using html tags. This will be referred to as the 'b' array. 3) Insert elements into array 'b' ensuring they are alwa ...

Do the values returned by window.screen.width and height represent CSS pixels or physical screen pixels?

After exploring the API named screen and visiting this documentation link, my initial anticipation was that I would receive information regarding actual screen size pixels. https://developer.mozilla.org/en-US/docs/Web/API/Screen/width https://i.sstatic.n ...

Discover which sub package is needed by running Npm check

While executing the command npm install, I encountered this error message: The package "getSnapshot-pkg-repo@^1.0.0" required by "conventional-changelog-core@^2.0.11" could not be found on the "npm" registry. I am uncertain about the source of this i ...

Dynamic Route Matching in NextJS Middleware

Currently, I am in the process of developing a website that incorporates subdomains. Each subdomain is linked to a file-based page using middleware. Take a look at how the subdomains are being mapped to specific pages: app.com corresponds to /home app.com ...

Magical Stylist - Eradicate Indicators while Preserving Labeling

Recently, I've been experimenting with the Google styling wizard in an effort to remove markers while retaining labels for businesses. My objective is to eliminate the marker icons but still display the text labels such as "Jimmy Johns," "Boone Saloon ...

The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data. My initial suspicion is that maybe the options are not being passed for the lines, but it seems like dataCollection is not being popu ...

Tips for aligning text vertically in flexbox arrangements

As I work on building my portfolio, I have implemented links as buttons using flexbox to make responsiveness easier. The height of these flexboxes is set dynamically using JavaScript with percentages. Despite trying various suggestions, none of them provi ...

Tips on personalizing the default html template in nuxt

Struggling to customize the default page from my Nuxt app due to limited documentation. Link to Documentation I'm interested in extracting only certain elements like the title or links in the head section. For example, how can I access just the li ...