Implement the LinkedIn API within an AngularJS application

I am a beginner in both Angular and JavaScript, and I am attempting to incorporate the LinkedIn API into my AngularJS project in order to automatically populate certain forms with data from LinkedIn. I have already tested it by including everything in the same file (in the view) like this:

 <script type="in/login" data-onAuth="onLinkedInAuth">  </script>
 <script type="text/javascript">

   function onLinkedInAuth() {
     IN.API
     .Raw('/people/~:(id,firstName,lastName,formatted-name,num-connections,location,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),summary,email-address,specialties)?format=json')
     .method('GET')
     .result(getResults)
     .error(onError)

   };

   function getResults(result) {
     console.log(result);
     document.getElementById('full_name').value = result.formattedName || '';
     document.getElementById('local').value = result.location.country.code || '';
     document.getElementById('summary').value = result.summary || '';
     document.getElementById('email_address').value = result.emailAddress || '';

   }

   function onError(error) {
     console.log(error)
   }
 </script>

But now I want to refactor this code to use services and controllers, something like:

Click LinkedIn Button -> controller -> Service -> linkeInAPI -> service -> controller -> view (populate forms with data, for multiple views in this case).

I have already created a linkedInService.js and linkedInController.js.

The issue is that I am unsure how to proceed with this, as I am new to all of these concepts. Any guidance would be greatly appreciated. Thank you.

Answer №1

Typically, an angularjs project consists of a variety of files serving different purposes.

Here is a suggested structure for organizing an angularjs project (sourced from this site). It is important to note that while this structure is not flawless, there are more optimal ways to organize angularjs code as explained in this article. However, this simple structure can serve as a starting point:

app/
----- controllers/ --> controllers connect html files with code logic
---------- mainController.js
---------- otherController.js
----- directives/
---------- mainDirective.js
---------- otherDirective.js
----- services/ --> reusable functions for controllers
---------- userService.js 
---------- itemService.js
----- js/
---------- bootstrap.js
---------- jquery.js
----- app.js
views/
----- mainView.html
----- otherView.html
----- index.html

To begin, you could centralize all linkedin-related code into a LinkedinService and utilize it within your controllers:

.service('LinkedinService', function ($http){

        this.loginWithLinkedin = function () {

         return IN.API
               .Raw('/people/~:(id,firstName,lastName,formatted-name,num-connections,location,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),summary,email-address,specialties)?format=json').method('GET')
        };

Then, call the service in one of your controllers:

LinkedinService.loginWithLinkedin().then(function (data) {
    console.log('linkedin login data:', data);

   })

You mentioned changing the DOM with

document.getElementById('email_address').value =
, which should be avoided in angularjs. Instead, utilize scopes for such tasks.

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 there a way to make a class method accessible in V8?

How can I make a class method accessible in a V8 context? I am trying to achieve something like the line below, but it's not working because lambda with captures cannot be treated as a function pointer. Global()->Set("foo",v8::FunctionTemplate::N ...

Can someone explain the function of statements such as (function () { // code; }.call(this)); within a JavaScript module?

By utilizing the Function.prototype.call() method, it becomes possible to create a function that can be applied to various objects. I delved into the code of , which had been minified and required to be un-minified for examination. The structure of the co ...

Tips for extending the space between one element and another when the width decreases:

Currently in the process of building a website using HTML/CSS/JS and have run into an issue. My front page features an image with text overlay, where the image has 100% width and a fixed height of 487px. I positioned the text using position:relative; and t ...

Creating functionality in Ionic to allow for the dynamic addition of buttons to the navigation bar

I have a navigation bar and I would like to include a save button on it for just one screen. After going through various blogs, I found that the general advice is to declare buttons in the view rather than accessing them in a controller. But still, isn&apo ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

How can I retrieve the specific error message from Express instead of seeing a generic status 500 error when a POST request fails in React?

In my React component, I am using a fetch with the post method to trigger a database update from an ExpressJS server. When the database update fails, I see the correct error message in the Express console, but in React, I only receive a 500 status error me ...

Why isn't preventDefault() effective in this particular situation?

When attempting to obtain an OTP, the event.preventDefault() function is functioning properly. However, after updating the register-form for OTP verification, the event.preventDefault() function ceases to work. How could this happen? Your assistance is gr ...

Angular XOR operation between two strings

I need to perform XOR operation on two strings and I found a python implementation for it: def sxor(s1,s2): return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2)) In the code above, a for loop is used to iterate over the strings and ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

Clear Vuex state upon page refresh

In my mutation, I am updating the state as follows: try { const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, { headers: { Accept: 'application/json', 'C ...

What is the best way to divide a string that contains n concatenated JSON strings in JavaScript or Node.js?

Imagine I receive the following string from a socket server (which is out of my control): {"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}} Because it contains 2 JSON strings, using ...

Difficulty encountered while developing personalized directives for image marquees in Angular

I have been trying to transfer a marquee of images into a custom directive. Originally, in my index file, I had a div structured like this: <div id="marquePic" style="width:90%"></div> and later in the script (end of body), I was implementing ...

changing the breadcrumb item to a dropdown item in a dynamic way

Hey there, I'm currently working on creating a breadcrumb item using Angular. Here is what I have so far: https://i.stack.imgur.com/zt5yX.png I decided to add a dropdown for the breadcrumb item, but I'm facing a challenge: I want to be able to ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...

Is there a way to confirm that a file has been chosen for uploading prior to form submission, by utilizing the jquery validator?

I have a section on my website where users can upload files. I am trying to implement validation to ensure that a file has been selected before the form is submitted. Currently, I am using the jQuery form validator plugin for handling form validations. Th ...

My react-native app is having trouble with modal closure

As I develop an app, I encounter an issue with Modal usage across different screens. I have created a universal component for handling all Modals. By passing JSX and toggling visibility based on a Global variable, the problem arises when switching screens. ...

What is the best approach for sending a binary image post request to an API using nodejs?

I am receiving the image binary in this manner: axios.get("image-url.jpg") Now, I want to utilize the response to create a new POST request to another server const form = new FormData(); const url = "post-url-here.com"; form.appe ...

Exploring methods for handling svgs incorporated in angular.js templates with webpack

I'm currently working on cache-busting my SVGs and other files like translation JSON. The issue I'm facing is that webpack does not seem to recognize imported svgs in the following format: <md-icon md-svg-src="assets/icons/ic-edit.svg">&l ...

"Utilize gulp-connect to store the root as an array

The gulp-connect documentation mentions that options.root can accept either an array or string. My situation involves having a build directory that I want to use as the root, along with a separate sources directory where all my source maps are located. Is ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...