Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following:

var token = $.get('/some-url', {}, someCallback);
token.oSomeObject = {data: 'some data'};

function someCallback( data, status, token ){
     token.oSomeObject.data // 'some data'
}

I utilize the token to store request-specific data.

In Angular, the only way I have found to achieve this is by storing the data in the actual config object:

var config = {
    url: '/some-url',
    method: 'GET',
    oSomeObject: { data: 'some data' }
};
$http(config).success(someCallback);

function someCallback( data, status, headers, config ){
     config.oSomeObject.data // 'some data'
}

This approach not only hinders the use of shorthand calls ($http.get, $http.post) but also seems more cumbersome when encapsulating the calls in a specific service module.

Is there an alternative method to address this issue?

Additional Clarification

It's possible that I am overlooking a simple solution regarding how to properly utilize the promise API. To ensure clarity, allow me to provide more context on the matter.

I have two files: 1) Controller.js and 2) AjaxServices.js (where all ajax calls are defined as methods on a service).

The content of AjaxServices.js is as follows:

app.service('AjaxService', function( $http ){
     var self = this;

     this.createUser = function( oUser, fSuccessCallback ){
          return $http.put('/api/user', {oUser: oUser})
                       .success(fSuccessCallback);
     }
}

As for Controller.js, it appears like this:

app.controller('MyController', function( $scope, AjaxServices ){
     $scope.saveUser = function( oUser ){
          var oPromise = AjaxServices.createUser( oUser, $scope.onUserSaved );

          oPromise.oUser = oUser // This is my workaround from using jQuery.ajax. 
                                 // The oPromise will be passed as the token object in the onUserSaved callback
     }
     $scope.onUserSaved = function( oStatus, status, headers, config ){
          oStatus.id // Here lies the id of the newly created user,
                     // which I aim to link with the local oUser object now

     }
}

How would you handle the same scenario utilizing the promise API?

Answer №1

UPDATE 2. Some insights on the new code: Instead of passing the callback to the service, let the service handle its task independently without being tied to any data consumer. This allows for attaching multiple callbacks to the same service $http call. Moving on to the controller as the data consumer:

app.service('AjaxService', function( $http ){
    var self = this;

    this.createUser = function( oUser ){
      return $http.put('/api/user', {oUser: oUser});
    }
}

With this approach, the service is not concerned with callbacks, opening up the possibility to attach multiple ones to a single service $http call. Now onto the controller:

app.controller('MyController', function( $scope, AjaxServices ){
  $scope.saveUser = function( oUser ){
    var originalPromise = AjaxServices.createUser( oUser );
    
    var modifiedPromise = originalPromise.then(function(response) {
      response.oUser = oUser; 
      return response;
    });
   
    modifiedPromise.then($scope.onUserSaved); 
  }
  
  $scope.onUserSaved = function(responseWithUser) {
    responseWithUser.oUser;
  }
}

It may seem clumsy to pass oUser through promises when it can be saved directly in the controller's scope and accessed from there.

UPDATE. It is possible to chain promises in any context. Here's an example of injecting a token using a service:

myModule.factory('Service', function($http) {
   return new function() {
      this.getData = function() {
        return $http.get(url).then(function(response) {
          response.token = myToken;
          return response;
        }
      }
   }
});

You can extend or wrap the $http service to inject tokens without services being aware. For multiple requests, consider using a $httpInterceptor. Learn more about intercepting http calls here

Original answer

Utilize the promise provided by $http to chain another promise that injects a token into the response:

myModule.factory('Service', function($http) {
   return new function() {
      this.getData = function() {
        return $http.get(url);
      }
   }
});

//in controller or other service:
var myToken;
var tokenizedPromise = Service.getData().then(function(response) {
  response.token = myToken;
  return response;
});

The final recipient of the promise also has access to the token

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

MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response. ControlledAutoComplete.jsx import { Autocomplete, TextField } from "@mui/mater ...

Strange JSON.parse quirk observed in Node.js when dealing with double backslashes

My coworker encountered an issue while trying to parse a JSON string from another system, leading to unexpected behavior. To illustrate the problem, I have provided a simple code snippet below: // This code is designed for node versions 8 and above con ...

The rendering of the input dropdown control in Angular JS is experiencing difficulties

I am currently using your Angular JS Input Dropdown control, and I have followed the code example provided on your demo page in order to implement the control on a specific page of my website built with PHP Laravel. However, I have encountered an issue dur ...

Implementing a Reset Button to Clear Checkboxes with PHP or JavaScript

I'm looking for help with setting up a button to reset the checkboxes on my preferences page. UPDATEL: Here's more information: The solutions provided should only affect checkboxes that are currently selected, not those enabled onLoad. This is ...

Run a Node command when the button is clicked

I am developing a web application where I need to run a node command upon clicking a button. Instead of manually executing the node command in the command line, I want it to be triggered by a click on the front end. For example: $( ".button_class" ).on( ...

Making an asynchronous request using Ajax to verify the status of a checkbox

I have two checkboxes, and I want to make an ajax call to a jsp page when one of the checkboxes is clicked. The jsp page should display a table with data fetched from a database. The issue arises when dealing with two checkboxes: <div class="search-in ...

Guide to invoking a server-side function through JSON data?

Here is the code I am working on: <script type="text/JavaScript> var myarray = new array(); function getsvg1() { $.ajax({ alert("hello"); type: "post", url: "WebForm1.aspx/getsvg1", ...

Missing Ajax Functionality in Laravel Application

The code snippet below was created by me... <script> $('#spielAuswahl').on('change', function(e){ console.log(e); var spielID = e.target.value; //ajax $get.('/spieler?spielID=' + sp ...

Executing jQuery script on dynamically loaded content

My website utilizes AJAX requests to load pages dynamically. One specific page includes a marquee script that I would like to implement. Unfortunately, due to the dynamic loading of the page, the marquee script is not functioning as expected. I have come ...

advancement in the $.when function

In an attempt to make an AJAX call utilizing the $.when and $.then functions, I am employing these features to populate a template. During this process, I aim to display a message in a form that states: "Loading data... please wait." I have come across ...

Is it appropriate to use a component inside an entry component?

I'm currently working on a component that triggers a function to open a window: @Component({ selector: 'app-deposits', templateUrl: './deposits.component.html', styleUrls: ['./deposits.component.scss&apo ...

looking to implement auto-scroll feature in flatlist using react native

I'm attempting to implement auto-scroll functionality in my FlatList, but I'm encountering a problem where the list does not scroll automatically. Additionally, whenever I try to manually scroll, it reverts back to index 0 every 5 seconds. Below ...

The ng-controller (dropdown menu) is functioning properly when tested locally and on JSFiddle, however, it is not working on

My HTML website with ng-app is functioning properly when tested locally and on certain coding platforms like JSFiddle and CodePen. However, it seems to encounter issues when deployed on Google Sites, Github, W3, and similar websites. The main functionalit ...

Error: Unable to assign values to undefined properties (specifically 'styles') when using withLess, withSass, or withCSS in next.config.js within Next.js

I have been attempting to set up a NextJS 12 project with custom Ant Design. Following some examples I found, it seems I need to configure my next.config.js file with the libraries @zeit/next-sass, @zeit/next-less, and @zeit/next-css. However, when I try t ...

Using ajax to submit a request to the controller

I'm currently developing an ASP.NET Core MVC application and have a registration page set up. My goal is to return View with errors if the model state is false: @model WebApplication2PROP.Entities.UserRegister @* For more information on enabling M ...

Encountering: Unable to break down the property 'DynamicServerError' of 'serverHooks' as it does not have a defined value

An error has arisen in a Nextjs app with TypeScript, specifically in the line of my react component which can be found here. This is my inaugural package creation and after several trials, I managed to test it successfully in a similar vite and TypeScript ...

The choices in the cell table selection are obscured due to the select table's height when opened

I am experiencing an issue with a table where each row contains two cells with "select" options. The problem arises when I open them, as they load within the table and the available options are not clearly visible. I can only view all the options by scroll ...

Is it possible to remove the browsing history of user inputs in JavaScript?

I'm currently working on a Simon Says game where the level of difficulty increases as players correctly repeat the pattern. However, I encountered an issue with clearing the input history that shows previous patterns entered by the user. How can I res ...

Updating the dynamic site script to be compatible with the newest version of the jQuery library

After finding a script on http://css-tricks.com/dynamic-page-replacing-content/, I decided to edit it to suit my needs. Initially, everything worked perfectly with "jquery-1.4.4". However, when I tried using versions later than "jquery-1.5", the active cla ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...