Guide to storing user data retrieved from the LinkedIn API into an Angularjs controller with the help of a personalized service

Hey there, I'm currently diving into Angular and facing a challenge with saving user information from LinkedIn API to the controller's scope without directly passing it to my custom service. It seems like that might not align with the best practices in Angular development.

//html

<script type="text/javascript" src="//platform.linkedin.com/in.js">
  api_key: *********
  onLoad: onLinkedInLoad
</script>

// linkedIn button

<script type="in/Login">
</script>

// app.js

angular.module("linkedinTestApp",[]);

function onLinkedInLoad(){
  eScope.$apply(function(){
    eScope.getLinkedInData();
  })
};

// main controller

var eScope;
angular.module("linkedinTestApp").
controller('mainCtrl',function($scope,linkedInService){
  eScope = $scope;

  $scope.getLinkedInData = function(){
    linkedInService.OnLinkedInFrameworkLoad($scope);
  }
})

//custom service

angular.module('linkedinTestApp')
.service('linkedInService', function() {
    var scope;
    this.OnLinkedInFrameworkLoad = function(s) {
      scope = s;
      IN.Event.on(IN, "auth", this.OnLinkedInAuth);
      console.log("Test1");
    }

    this.OnLinkedInAuth = function() {
      IN.API.Profile("me").result(function(result){
        console.log(result);
        var profile = {
            vnaam: result.values[0].firstName,
            anaam: result.values[0].lastName,
            foto: result.values[0].pictureUrl,
            headline: result.values[0].headline,
            id: result.values[0].id
        }
        console.log(profile);
        scope.profile = profile;
      });
      console.log("Test2");
    }
});

Answer №1

After diligently testing the code, I spent about 20-30 minutes obtaining the API key. Just as I was about to test an answer, someone else had already posted a similar solution. Despite not being the most elegant approach for retrieving the profile in the controller, I opted to make minimal changes to the existing code for simplicity.

angular.module("linkedinTestApp",[]);

function onLinkedInLoad(){
  eScope.$apply(function(){
    eScope.getLinkedInData();
  })
};

// main controller

var eScope;
angular.module("linkedinTestApp").
controller('mainCtrl',function($scope,linkedInService){
  eScope = $scope;

  $scope.getLinkedInData = function(){
    linkedInService.OnLinkedInFrameworkLoad().then(function(profile){
      console.log('response ', profile);
  });
  }
})

//custom service

angular.module('linkedinTestApp')
.service('linkedInService', function($q) {
    this.OnLinkedInFrameworkLoad = function() {
      var deferred = $q.defer();

      IN.Event.on(IN, "auth", function(){
        deferred.resolve(OnLinkedInAuth())
      });
      return deferred.promise;
    }

    function OnLinkedInAuth() {
      var deferred = $q.defer();

      IN.API.Profile("me").result(function(result){
        console.log(result);
        var profile = {
            vnaam: result.values[0].firstName,
            anaam: result.values[0].lastName,
            foto: result.values[0].pictureUrl,
            headline: result.values[0].headline,
            id: result.values[0].id
        }
        deferred.resolve(profile);
      });
      return deferred.promise;
    }
});

Answer №2

// controller

    angular.module("linkedinTestApp").
    controller('mainCtrl',function($scope,linkedInService){

      $scope.retrieveLinkedInInfo = function(){
        linkedInService.OnLinkedInFrameworkLoad().then (function (result) {
             $scope.profileData = result;
        });
      }
    })

    //service for LinkedIn integration

    angular.module('linkedinTestApp')
    .service('linkedInService', function() {
        this.OnLinkedInFrameworkLoad = function() {
          return this.OnLinkedInAuth();
        }

        this.OnLinkedInAuth = function() {
          return IN.API.Profile("me").result(function(result){
            console.log(result);
            var userProfile = {
                firstName: result.values[0].firstName,
                lastName: result.values[0].lastName,
                profilePicture: result.values[0].pictureUrl,
                professionalHeadline: result.values[0].headline,
                userID: result.values[0].id
            }
            console.log(userProfile);
            return userProfile;
          });
        }
    });

Answer №3

Here is a suggestion for you:

angular.module('linkedinTestApp').service('linkedInService', function($q) {
    var deferred = $q.defer();
    var self = this;
    this.profile = null;

    this.OnLinkedInFrameworkLoad = function() {
      IN.Event.on(IN, "auth", this.OnLinkedInAuth);
      console.log("Test1");
    } // It's unclear if this function is necessary or who calls it; you may just replace it with the next line:
    // IN.Event.on(IN, "auth", this.OnLinkedInAuth);

    this.OnLinkedInAuth = function() {
      IN.API.Profile("me").result(function(result){
        console.log(result);
        deferred.resolve( {
            vnaam: result.values[0].firstName,
            anaam: result.values[0].lastName,
            foto: result.values[0].pictureUrl,
            headline: result.values[0].headline,
            id: result.values[0].id
        } );
      });
      console.log("Test2");
    }

    this.instance = function() {
         return deferred.promise;
    }
});

Implement in your controller like this:

$scope.linkedInService.instance().then(
   function(profile) {
       console.log(profile);
   }
);

This code has not been tested yet, but hopefully, it will work as expected...

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

Search for text within the nearest <p> tag using HTML and jQuery

My table contains different td elements with the same ID, as shown in this foreach loop: <td class="AMLLeft" style="display:inline-block; !important">ID: <p class="important">${item.id}</p> </td> <td align="right" nowrap="tr ...

Issue encountered while attempting to utilize setStart and setEnd functions on Range object: Unhandled IndexSizeError: Unable to execute 'setEnd' on 'Range'

Every time I attempt to utilize a range, an error message appears in the console: Uncaught IndexSizeError: Failed to execute 'setEnd' on 'Range': The offset 2 is larger than or equal to the node's length (0). This is the script I ...

Clicking on an absolute HTML element will instantly scroll back to the top of the page

Working on a website, I've designed a custom menu that is hidden with 0 opacity and z-index -1. When a button is clicked, the menu will appear on the screen. You can visit to see the site in action. The issue I'm facing is that every time I cl ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

The method by which JavaScript identifies when a Promise has resolved or rejected

How does JavaScript determine when the state of myPromise has transitioned to "fulfilled" in the code provided below? In other words, what is the process that determines it's time to add the .then() handler to the microqueue for eventual execution? co ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

It seems that there is an issue with accessing the root directory while utilizing the yo

I'm currently working on setting up the Yeoman 1.0 beta's angular scaffolding and have been following these steps in my workflow: npm install generator-angular generator-testacular # installing generators yo angular # creati ...

Refreshing the information in the database table

Upon receiving data from the server using ajax, I populate this table: $.each(data, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td>" +data[i].A+ "</td><td>" +data[i].B ...

When running the PHP script, the output is shown in the console rather than in the

Here is a PHP script snippet that I am working with: <?php add_action('wp_ajax_nopriv_getuser', 'getuser'); add_action('wp_ajax_getuser', 'getuser'); function getuser($str) { global $wpdb; if(!wp_verif ...

Using Jquery to create an array containing all the items in the pager

192.168.1.1/home?page=1, 192.168.1.1/home?page=2, 192.168.1.1/home?page=3. Is there a way to create an array of only the new items on the pager? I am interested in storing only the elements with the class item-new into the array. To clarify further: I n ...

The significance of API Input Validation and Steering Clear of Lengthy Conditional Statements

Currently, I am working on ensuring that my API functions correctly even in cases of bad or missing data. At the moment, I have an if statement that checks for any missing inputs. If an input is missing, it returns false, otherwise there is a large else b ...

The table appears to be fixed in place and will not scroll, even though the data

Previously, my code was functioning perfectly with the mCustomScrollbar I implemented to scroll both vertically and horizontally on my table. However, while revising my jQuery code for organization purposes, I seem to have unknowingly altered something tha ...

Is it possible to execute asynchronous queries within a map function in Mongoose?

Currently, I am struggling to create queries using a .map function, pushing the results to an array and then returning it. The issue is that the array always ends up empty due to the asynchronous nature of the operation. Although I attempted using async/ ...

Maximizing for-loop efficiency: the advantage of caching array length

Let's compare two variations of a loop iteration: for (var i = 0; i < nodes.length; i++) { ... } and var len = nodes.length; for (var i = 0; i < len; i++) { ... } Would the second version be faster than the first one in any way? ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...

Having trouble with the Twitter share count URL - seeking out other options

Previously, I utilized the following Javascript function to retrieve the Twitter share count for a URL. Unfortunately, Twitter has discontinued providing the share count. Is there a more effective alternative available? // Twitter Shares Count $.getJSON ...

Tips for refreshing $('select') with .material_select() once the $http request is finished

Currently, I am utilizing Angular and Materializecss for my project. I am facing an issue where I want to update material_select() after the completion of $http request, but I have been unable to find a suitable solution so far. Here is what I have attemp ...

Issue with Angular: Nested directive parameters are showing as "undefined" and not getting passed correctly

We are currently using a modified version of the example to suit our specific requirements. In our modal view(.jsp), we have integrated a directive named 'querybuilder' which is represented by the Yellow part in the image (a js file). The contr ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...