Having issues with my AngularJS application not updating as expected

After creating a custom service to store all search parameters, I can easily access them from any part of my code. This ensures that the search parameters are always accurate. Below is the definition of the custom service:

App.factory('filterService', function () {
  var FilterService = {
    actorId: '0001234',
    actionStatus: ['BUILDING', 'STARTED', 'SENT'],
    payer: null,
    limit: 10,
    offset: 0,
    sortBy: null,
    filterBy: null,
    actionType: ['EB', 'AUTH'],
    actorType: 'REQUESTING'
  };

  return FilterService;
});

When making a call to my REST service, I can utilize the search criteria stored in the custom service as demonstrated below:

App.factory('encounterService', function ($resource, filterService) {
  return {
    resource: $resource('/internal/v2/encounters/:encounterId', {encounterId:'@encounterId'}, {
      search: {
        method: 'GET',
        headers: {
          'RemoteUser': 'jhornsby',
          'Content-Type': 'application/json'
        },
        params: {
          actorType: filterService.actorType,
          actorId: filterService.actorId,
          actionStatus: filterService.actionStatus,
          actionType: filterService.actionType,
          limit: filterService.limit,
          offset: filterService.offset,
          payer: filterService.payer,
          filterBy: filterService.filterBy,
          sortBy: filterService.sortBy
        }
      };
    }
  });

To execute the search function, I make the following call:

encounterService.resource.search({}, function(data) {
  // perform actions on data
});

However, when updating the filterService values from a controller, the changes do not reflect in the filterService. An example of updating the filterService is shown below:

$scope.ok = function() {
    // Update the filter items using this.model
    filterService.actorId = $scope.model.actorId;
    filterService.actionStatus = $scope.model.actionStatus;
    filterService.actionType = $scope.model.actionType;
    filterService.limit = $scope.model.limit;
  }

Whenever I call search, it still uses the default values. How can I transform the search parameters into an object as intended?

Answer №1

The issue lies in the fact that the return statement in your encounterService function is only executed once during module initialization. Consequently, the values of the params field on the search object are set at this initial point and remain static. To overcome this limitation, you need a method to evaluate the params object each time a query is made. One solution is to modify the code so that it returns a function which can be invoked to retrieve the resource instead of returning the resource directly.

For instance:

App.factory('encounterService', function ($resource, filterService) {
  return {
    getResource: function () {
      return $resource('/internal/v2/encounters/:encounterId', {encounterId:'@encounterId'}, {
        search: {
          method: 'GET',
          headers: {
            'RemoteUser': 'jhornsby',
            'Content-Type': 'application/json'
          },
          params: {
            actorType: filterService.actorType,
            actorId: filterService.actorId,
            actionStatus: filterService.actionStatus,
            actionType: filterService.actionType,
            limit: filterService.limit,
            offset: filterService.offset,
            payer: filterService.payer,
            filterBy: filterService.filterBy,
            sortBy: filterService.sortBy
          }
        }
      };
    }
 }});

You can then use it like this:

encounterService.getResource().search({}, function(data) {
      // process the data
});

Answer №2

If you want to use filterService as an OO object with getter and setter methods, it would make handling your service object easier and improve code readability.

Here's an example:

App.factory('filterService', function () {
  this.FilterService = {
    actorId: '0001234',
    actionStatus: ['BUILDING', 'STARTED', 'SENT'],
    payer: null,
    limit: 10,
    offset: 0,
    sortBy: null,
    filterBy: null,
    actionType: ['EB', 'AUTH'],
    actorType: 'REQUESTING'
  };

   this.getFilterService(){
     return this.FilterService;
   }


  this.setFilterService(service){
    this.FilterService = service;
  }
});

Now from the controller, you can set the service using:

filterService.setFilterService(dummyService);

and get the service using:

$scope.theService = filterService.getFilterService();

I hope this approach works for you.

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

Display a specific number of page indicators on the Flickity plugin

Currently, I am utilizing the flickity plugin to create a slideshow feature on my website. My goal is to display navigation dots on the images to facilitate user interaction. If you are interested, you can access the plugin through this link: I would lik ...

Ways to switch the positions of two characters in a text box

Is there a way to access the text content of a textarea and swap the two characters around the cursor using Javascript? I am interested in creating a Chrome extension that will allow me to quickly correct typos in Gmail. (I am assuming that the main editin ...

Issue with React Material UI: Snackbar is closing when Dialog closes which is not the intended behavior

When using Material UI dialog, it unexpectedly closes the snackbar as well. To illustrate this strange issue, I have prepared a demonstration: https://codesandbox.io/s/react-hooks-counter-demo-v20w3 I am passing states from the parent component to the c ...

Tips for utilizing jQuery Ajax data action

I've been trying to understand how to effectively utilize the data parameter in a $.Ajax call. However, I am facing confusion regarding the 'action' part within the data call. Is it meant to trigger an action in a controller? If so, how can ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

Exploring the functionalities of the execPopulate() method

I'm hitting a roadblock with using execPopulate. I've gone through the documentation, but it's just not clicking for me. Could someone clarify when exactly execPopulate() should be used after populate() and when it's unnecessary? In s ...

Function in Typescript used for checking types and catching compilation errors from external sources

Fact: I am currently using TS version 2.3.4. I have developed a function that checks if a variable is defined (it takes the parameter variable and returns 'undefined' !== typeof variable). It's quite simple. export function IsDefined(variab ...

Instructions on converting text to a Float value and displaying the calculated result in a separate div

I am attempting to extract a string from a div, clear its content, then retrieve the actual price from ".skuBestPrice", remove any special characters, perform calculations to convert it into a floating point number, and display this number in the div ".tot ...

Creating a timer implementation in Node.js using Socket.IO

In the process of developing a drawing and guessing game using node.js and socket.io, I have a structure consisting of a Room class, a Game class (which is an extension of Room), and a Round class where each game consists of 10 rounds. During each round, a ...

On Linux systems, Node.js in JavaScript interprets strings as objects only

I'm encountering an issue with my Discord.io bot. I am attempting to run it on a Linux server, but the Linux version of Node.js keeps treating the contents of a string as a separate object, leading to the following TypeError: TypeError: Object IT&apo ...

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...

What is the best way to combine a new object with an existing array of objects in JavaScript?

https://i.sstatic.net/QIRzO.png Here is an array that I need to modify by adding the object {"temperature":{"work":30,"home":24}} to the beginning: 0 : {title : "tptp", {"temperature":{"work":30,"home":24}}, lastview:"12-12 21:2"} The code I am using is ...

Are you constantly encountering errors with JSONP when working in Angular?

Upon checking the web console, I noticed that the jsnop file is being loaded but I also receive an "ajax Failed" message. var loginuser = $http.jsonp( 'http://livegap.com/interior/users/login.php?callback=JSON_CALLBACK', { params :{username: "us ...

Adding legends to AmSerial charts is a simple process that enhances the readability and

Incorporating Amcharts into my AngularJS Application has allowed me to effortlessly generate a basic bar chart. Check out the snippet of code from my controller below: let empChart; let empBarGraph; let empLine; co ...

The Document.querySelector() method is not displaying every element

As a beginner, I am currently exploring the world of relative CSS selectors and JSPath for my automation scripts. During my journey, I noticed that there are differences in the return statements between these two methods. Below is an example demonstrating ...

By executing array1.splice(1,1), I am deleting elements from array2 that was generated by copying array1 with array1.slice(0)

I was working with JSON data and converted it into an array of objects. Then, I assigned that array to another array using the .slice(0) method. However, I encountered an issue where when I tried to remove an element from the assigned array, it also remov ...

Redux state assigns object to another object

I started with an initial state that looks like this: let initialState = { items: [ { name: 'a' }, { name: 'b' } ], otherItems: [] } I am attempting to copy the items array and assign i ...

The lightbox feature on the page is not functioning properly

On my website, I have a beautiful lightbox created using fancybox.net. You can check it out here: I also use gallery codes to display images in a gallery format. Below is the jQuery code I am using: $(document).ready(function() { $(".gallery").fancy ...

JSplumb - retrieve a connection targeting a particular endpoint

There are multiple endpoints on my elements. By using the following code snippet, I am able to retrieve all the connections linked to a specific element: // My JSPlumb instance object is named plumber connSet = plumber.getConnections({target:eltID}); Th ...