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

Is it possible to utilize an await in an rxjs observable?

Implementing an interceptor for my HTTP requests requires the use of the access token from the user instance. Within my app component, I initialize the user: app.component.ts private async restoreUser(): Promise<UserModel | any> { // ... some vi ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

What could be causing this jQuery selector to not select any elements?

Here's a simple question with some code that needs troubleshooting: $insides = $('<thead><tr><th><!--Blank space --></th></tr></thead><tbody><tr class="green-row"><td>Opportunities to D ...

Wait until the npm.load callback is returned before returning module.exports

I am currently facing a situation similar to the one depicted in this simplified example. main.js var settings = require('../settings.js'); console.log(settings.globalData); //undefined The settings.js file relies on an external module (npm) t ...

What is the proper way to construct a URL with filter parameters in the RTK Query framework?

I am facing difficulty in constructing the URL to fetch filtered data. The backend REST API is developed using .Net. The format of the URL for filtering items is as follows: BASE_URL/ENDPOINT?Technologies=some-id&Complexities=0&Complexities=1& ...

Positioning the image to appear behind the Canvas

As I near the end of the game, I'm encountering an issue where the background image overlaps the Canvas. How can I resolve this problem? -Translated by Google Link to game Link to game with background ...

Elegant Box 2 - Ascending to the top when clicked

I am excited to share that I am using FancyBox for the first time in my project. This time, I decided to separate the image from the link for a unique user experience. The hover effect works perfectly fine - the issue arises when the link is clicked and th ...

What is the process for removing an item from a JSON file using an HTTP DELETE request in a Node.js environment?

Essentially, I have a JSON file containing user and group data and I need to delete a specific group from it. Below is a snippet of the JSON file named authdata.json: [{ "name": "Allan", "role": ["Group Admin", "Super Admin"], "group": ["Cool- ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

Issue with React.js: The formData is empty when trying to add a value from a file using material-ui-dropzone

I am currently working on integrating an upload feature using a library named material-ui-dropzone Although I believe the file upload process is functioning correctly, I encounter an issue with axios where the formData appears empty even prior to sending ...

Is Jquery struggling to modify the visual enhancements?

Check out this link, I need the sidebar design to be similar to what is shown in the provided link. Furthermore, I am looking for a way to have a pointer that follows along with my selection on different labels such as home, charts, etc. Can anyone assis ...

Scrolling in iOS 8 causing flickering problem with background image

Utilizing the Supersized jQuery slider plugin to create a full-page background slider with a fade-in effect and added height for scrolling. The slider functions correctly on desktop, but upon testing on an iOS 8 iPad device, there is noticeable flickering ...

Trouble displaying loaded JSON data with $http GET in ng-table

I have recently delved into learning angularjs and am currently experimenting with using ng-table to display the results of blast searches. Everything runs smoothly when I directly add the JSON data in the JavaScript script. However, I have been unsuccess ...

Using jQuery, check if the input contains any phrases from the array that are suitable for children

I stumbled upon some code designed for a chat system. My plan is to implement it as a child-friendly global chat, so that I can avoid any blame associated with inappropriate content. The basic premise of the code involves checking user input against an arr ...

The onClick function is called when I fail to click the button within a React form

I set up a form and I would like to have 2 ways to submit it: One by filling out the input field and pressing enter One by recording voice (using the react-speech-recognition library) However, after adding the second way, the input fi ...

The background color of the active tab is updated upon loading the page

I have attempted to modify this code to change the background color of li tag on click. It successfully changes the background color when hovering or clicking, but unfortunately reverts back to the default color upon page refresh. I am looking for a soluti ...

Execution of scripts upon completion of document loading via AJAX

When loading a portion of HTML through AJAX, my expectation was that the JavaScript code inside would not run because it is dependent on the DOM being ready. However, to my surprise, the code within document.ready is still executing. I have even placed a ...

When attempting to pass data to a modal, an error occurs due to props being undefined. This results in a TypeError with the message "Cannot

I'm working on a product listing feature where each item displays some information along with a "more details" button. When the button is clicked, a modal window opens to show additional details of the specific product (using props to pass data betwee ...

What is the best way to ensure that all the divs within a grid maintain equal size even as the grid layout changes?

I have a grid of divs with dimensions of 960x960 pixels, each block is usually 56px x 56px in size. I want to adjust the size of the divs based on the changing number of rows and columns in the grid. Below is the jQuery code that I am using to dynamicall ...

Reposition div when clicked

I have encountered a challenge where I am unable to perform a small task. My goal is to have the position of "div1" change upon clicking on "div2", taking into account that "div2" is nested inside "div1". Additionally, when clicking on "div2" again, "div1" ...