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

The controller and node js request associated are invisible to my HTML page

Here is my HTML code. I have just created a unique controller for a specific part of the code. <div class="mdl-grid" ng-controller="ValueController"> <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col"> <div class ...

What is the correct way to properly insert a display none attribute

I'm experiencing some alignment issues with the images in my slideshow. I used this example as a reference to create my slide: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_dots When clicking on the next image, it seems to mo ...

Managing the file order within subdirectories for Rails assets

Utilizing rails to power a primarily single page application, I am incorporating angular as well. Within my assets/javascripts directory, I have organized folders for controllers, directives, filters, routes, services, and more. Certain elements, such as ...

Exploring, navigating, and cycling through JSON in Node.js

I'm currently attempting to extract the titles of front page articles from Reddit's RSS feed and running into some issues. Below is the snippet of code I am working with: //var util = require('util'); //var cheerio = require('chee ...

Validating ReactJS properties

Transitioning from ReactJs to React-Native, I came across this function structure in a react-native button code by Facebook: class Button extends React.Component<{ title: string, onPress: () => any, color?: ?string, hasTVPreferredFocus?: ?bo ...

Perform a jQuery AJAX GET request while passing the current session information

Is it possible to retrieve the HTML content of another webpage using jQuery, particularly when that page is already signed in? In simpler terms, can we use $.get() to fetch a different page on the same website and transfer the PHP/Javascript cookies with ...

Angular-maps-google search bar

I have a specific directory structure as follows: myFolder myApp.coffee index.html searchbox.tpl.html Within myApp configuration, I've set the following: $scope.searchbox = {template: "searchbox.tpl.html"} While trying to implement this example, ...

What is the best way to create a form that includes both dynamic objects and dynamic arrays using a JSON schema?

I have observed how a JSON schema can be utilized to construct dynamic arrays. My goal is to develop a JSON web form using a JSON schema that allows for objects (dictionaries) to be expandable similar to arrays. For example, you can visit the demonstrati ...

Visualizing Data with Flot.js - A Comprehensive Guide

Does anyone know how to organize values in a flot histogram by day, merging them into one bar per day? I've been searching for a solution but can't seem to find one. __ If you have any ideas, please share! ...

Is it advisable to incorporate vue-resource in Vuex actions?

I am currently working on a web application that retrieves airport data from the backend. To manage states and data sharing, I am utilizing Vuex. My dilemma is whether to load the airports in my Vuex actions or within a method of my Vue instance which will ...

Avoid displaying duplicate items from the array

Utilizing react js, I am attempting to iterate through an array of objects and display the name of each object in the array: const arr = [ { name:"Bill", age:88 }, { name:"Bill", age:18 }, { name:"Jack", age:55 }, ] ...

Instead of returning an object, the underscore groupBy function now returns an array

Currently, I am attempting to utilize underscore to create an array of entities that are grouped by their respective locations. The current format of the array consists of pairs in this structure { location: Location, data: T}[]. However, I aim to rearran ...

Changing an object received as a prop in Vue.js

Is it acceptable to mutate values in a prop when passing an Object reference? In the process of developing a web application that involves passing numerous values to a component, I am exploring the most efficient method of handling value passing between c ...

I wonder what the outcome would be if I used res.send to send a JSON file instead of res.json

Is it possible to send a JSON file using res.send in NodeJs instead of res.json? What are the potential consequences of doing this and why is it recommended to avoid this practice? ...

What is the method for defining the maximum stack size in a node.js environment?

I encountered an error when trying to convert a docx file to epub format. Despite increasing the stack size, the task was unsuccessful. The specific error message I received is as follows: RangeError: Maximum call stack size exceeded at Array.filter (n ...

What specific URL should be included in a JavaScript ajax request?

As I delve into creating a JSON file using an ajax request in javascript, confusion strikes when it comes to determining the appropriate URL. With no previous experience working server side and relying on WAMP server 3.0.6 to host my project-in-the-works ...

I'm noticing that my CSS is behaving differently than expected. Despite setting position: absolute, the output is displaying as inline-block instead of block. Why is this happening

div { width:200px; height:200px; position: absolute; } .first-container { background-color: #9AD0EC; } .second-container { background-color: red; left: 200px; } .third-container { background-color: blue; left:400px; } Despite setting th ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...

Notification for background processing of $http requests

I am searching for a solution to encapsulate all my AJAX requests using $http with the capability to display a loading gif image during processing. I want this functionality to extend beyond just $http requests, to cover other background processing tasks a ...

A platform for creating ER and flow diagrams specifically tailored for web applications, utilizing open source software

Our team is currently working on creating a web application that enables users to create diagrams, such as flow or ER diagrams. We are looking for ways to convert these diagrams into XML or other formats for representation. Are there any open-source soft ...