Angular JS - Implementing a flexible URL structure for fetching data using $http GET

I have been working on implementing a login feature for my app by using a custom REST API. Initially, I was able to successfully authenticate by manually entering the complete URL with the username and password:

http://www.myexample.com/ACTION/USER/PASSWORD/

However, I now need to retrieve the data from the input fields of my form. Here is the function code from my controller:

$scope.authenticate = function(selectedUs, selectedPw){
  $scope.remoteData = null;
  
  dataService.getData(function(data) {
    $scope.resultAPI = data;
    $scope.username = $scope.resultAPI.username;
    $scope.id_user = $scope.resultAPI.id_user;
    $scope.isauthenticated = $scope.resultAPI.isauthenticated;
    $scope.user_role = $scope.resultAPI.user_role;
    $scope.complete_name = $scope.resultAPI.complete_name;
  });
}

Below is the service code handling the request:

.service('dataService', function($http) {
   delete $http.defaults.headers.common['X-Requested-With'];

   this.getData = function(callback) {
     var myparams = {a: '', u: '', p: ''};
     myparams.a = 'ZW50cmFy';
     myparams.u = 'anRk';
     myparams.p = '899960d8dd39b29e790845912cb35d96';
     
     $http({
       method: 'GET',
       url: 'http://www.adagal.net/api_adagal/api.php',
       withCredentials: false,
       params: myparams,
       headers: {
                 'Content-Type': 'application/json; charset=utf-8'
       }
    }).success(function(data, status, header, config){
       callback(data);
    }).error(function(){
       $scope.remoteData = null;
       return "Connection Error";
    });
  }
});

I am currently exploring different methods to construct the URL dynamically based on user input. How can I achieve this in an effective manner?

Answer №1

Do you need to pass the username and password through the URL, or via post/get data?

Regardless, you will have to provide the username and password to the service. This can be achieved by passing them in the service function.

this.retrieveData = function(username, password, callback) {
    ...
  })...
}

When making the call:

dataService.getData($scope.username, $scope.password, function(){...});

Answer №2

From what I gather from your query, it seems like making adjustments to your service is necessary:

.service('dataService', function($http) {
   delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(URL, callback) {
     var myparams = {a: '', u: '', p: ''};
     myparams.a = 'ZW50cmFy';
     myparams.u = 'anRk';
     myparams.p = '899960d8dd39b29e790845912cb35d96';
     $http({
       method: 'GET',
       url: URL,
       withCredentials: false,
       params: myparams,
       headers: {
                 'Content-Type': 'application/json; charset=utf-8'
       }
    }).success(function(data, status, header, config){
    // Upon successful data retrieval, execute the callback
       callback(data);
    }).error(function(){
       $scope.remoteData = null;
       return "Connection Error";
    });
  }
});

To utilize this service, you should do the following:

var url = "http://wwwmyexample.com/ACTION/"  + $scope.selectedUs + "/" + $scope.selectedPw + "/"
  dataService.getData(url, function(data) {
  $scope.resultAPI = data;
  $scope.username=$scope.resultAPI.username;
  $scope.id_user=$scope.resultAPI.id_user;
  $scope.isauthenticated=$scope.resultAPI.isauthenticated;
  $scope.user_role=$scope.resultAPI.user_role;
  $scope.complete_name=$scope.resultAPI.complete_name;
});

Your HTML structure should include something similar to this:

<input ng-model="selectedUs" />
<input ng-model="selectedPw" />

Answer №3

Appreciate everyone for sharing their insights. I managed to identify my mistake:

 dataService.getData(function(u, p, data) {

Here is where I went wrong:

 dataService.getData(u, p, function(data) {

I erroneously placed u and p next to data, a mistake that cannot be overlooked. Much gratitude for all the assistance.

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

Short-circuiting async flows on non-error events in Node.js

Node implements the CPS convention for callbacks. Typically, when a function encounters an error, it is common practice to either handle the error or callback the error to the parent function by utilizing something like return cb(err). One challenge I fac ...

Monitoring the actions that occur when my button is clicked using Firefox and Javascript

Whenever I click on a few new buttons that I've recently added, something weird is happening. The buttons are functioning correctly, but they keep scrolling the page back to the top. I suspect that there might be some interference from another part of ...

When using the `console.log()` function in JavaScript, the table formatting may

I'm attempting to generate a table using JavaScript Here's the HTML for the table: <table id="rounded" runat=server summary="2007 Major IT Companies' Profit" style="position:relative;left:-45px;" > <tr> <th sc ...

The class is failing to be applied to the parent div that holds an id starting with the letter x

I have been attempting to assign a class to the parent container when the child element has the 'hidden' class. If not, then a different class should be added. function tagMissions() { if ($('span[id^="mission_participant_new"]').h ...

Tips for implementing an element onClick change within a Redux container using React.js

After coming across a similar question by another user on this link, I found the answer quite clear. However, if you're dealing with a redux container, the states are transformed into props via the mapStateToProps function. So, my query is: how shoul ...

Ways to modify a mongoose find query to return null instead of throwing a CastError in case of incompatible types

Issue When utilizing mongoose to search for docs by a particular field, if the data type of the field differs from the data type of the queried value, mongoose will try to convert the query value to match the field's data type. However, if the conve ...

Unleashing the Power of Vuejs: Setting Values for Select Options

I have a specific requirement in my Vue application where I need to extract values from an XLS file and assign them to options within a select dropdown. Here is what I currently have: <tr v-for="header in fileHeaders" :key="header"&g ...

Ways to iterate over $firebaseArray

After creating an array of users using the following code - var ref = new Firebase(FIREBASE_URL + '/users'); var users = $firebaseArray(ref); I populated this array with objects and now I need to iterate through each user in the controller. Wh ...

Tips for steering clear of getting caught in the initial focus trap

I have implemented Focus-trap (https://www.npmjs.com/package/focus-trap) in my modal to enhance keyboard accessibility. Here is a snippet of my code: <FocusTrap focusTrapOptions={{onDeactivate: onClose}} > <div> ... </div> <Focu ...

Error: The property 'fixtures' of an undefined object cannot be accessed. This issue arose from trying to access nested JSON data after making

Struggling with asynchronous calls, JS, or React? Here's my current challenge... Currently, I am using the fetch library to display a table based on data structured like this (note that there are multiple fixtures within the fixtures array): { " ...

Trouble with the datepicker

I tried using the datepicker from and followed its demo, but unfortunately, the datepicker is not showing up on my page. I have gone through everything carefully, but I am unable to identify the reason behind this issue. Could someone please assist me i ...

Store Dark Mode preferences in the browser's local storage using React and Material-UI

Is there a way to save the dark mode setting in localStorage? Can this approach be used for storing it? Any suggestions on how to achieve this would be appreciated. Thanks, cheers! function App() { const [darkState, setDarkState] = useState("&qu ...

Displaying Component when Clicked using Vue.js

How can I display a modal component after an "on click" event? Is it possible to show a component using a method call, or what is the recommended approach in this scenario? Here is my specific use case: I have multiple cards each containing various infor ...

The code is throwing an error because it is unable to find the property 'vibrate' of an

I am currently trying to implement the ng-cordova vibrate plugin in my ionic application, but I am facing an issue. The console log is showing an error message: Cannot read property 'vibrate' of undefined. Can someone please provide guidance on h ...

Explore the next page on the API response by navigating to another page

In my next app, I have a versatile function called postAPI, which is used to send requests to the backend server. import Router from 'next/router'; export const postAPI = async ( endpoint, data = {}, headers = {}, method = 'POST&apos ...

Front-end app (AngularJS) struggling to receive correctly encoded files from Web API

I have a Base64 encoded string that contains a word document (generated by thunderHead). I decode it using the following code: byte[] dataBytes = Convert.FromBase64String(data) When I write this byteArray directly into a file: File.WriteAllBytes("myFile ...

Combining multiple HTML elements onto a single page with just one function

I am trying to dynamically import specific HTML content into a new page, rather than the entire page itself. The issue I am encountering is that I have to create a document load function for each individual item I want to import. Is there a more efficient ...

Guide to emptying session storage with a service

When working with AngularJS, I have implemented a logout button. Currently, I am using window.sessionStorage.clear() to clear the session storage. However, I would like to utilize a service called LocalCacheService to achieve this task instead. How can I c ...

The view has no access to $scope but the controller does

I need to display the iso code using a $scope when selecting a country from a list. The list of countries is fetched through a $http call in a factory and then stored in a scope. ///////// get countries //////////////// tableFactory.getCountries().then(f ...

Troubleshooting HTML/JavaScript with JSP and JSTL: iPhone only displaying the first option in select dropdown, rather than the selected option

My HTML includes a <select> element: <select id="mySelect"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> ...