Angular code is failing to send a signal to the server following a $http.post request

I've been using angular for about a week now and I've been struggling to solve this issue. I have a service that wraps around $http because multiple controllers make calls to the same URL. On one particular page, there is a lot of server-side business logic happening on a post request, so I want to trigger a $route.reload(). It seems like it's working because after vm.saveItem() the controller is reinitialized, but the $http.get() call doesn't actually send the signal to fetch new data from the server. What am I missing?

  myModule.factory("itemRepository", function ($http) {

    var baseUrl = "/api/inventory";

    return {
      getLocations: function (itemName) {
        return $http({
          url: baseUrl + "/" + itemName + "/locators",
          method: "GET",
          cache: false
        });

      },
      addNewLocator: function (itemName, newLocator) {
        return $http.post(baseUrl + "/" + itemName + "/locators", newLocator);
      }
    };

  });




// itemEditorController.js

(function () {
  "use strict";

  angular.module("app-inventoryitems")
    .controller("itemEditorController", itemEditorController);

  function itemEditorController($routeParams, $route, itemRepository) {

    // initialize vars
    var vm = this;
    vm.itemName = $routeParams.itemName;
    vm.errorMessage = "";

    // Models
    vm.items = [];
    vm.isBusy = true;

    vm.newLocator = {};
    vm.newLocator.name = vm.itemName;

    // PROBLEM HERE, does not call server after post new data 
    // and $route.reload() was called
    itemRepository
      .getLocations(vm.itemName)
      .then(function (response) {
        angular.copy(response.data, vm.items);
      }, function (err) {
        vm.errorMessage = "Failed to load batches.";
      })
      .finally(function () {
        vm.isBusy = false;
      });

    vm.saveItem = function () {
      vm.isBusy = true;

      itemRepository.addNewLocator(vm.itemName, vm.newLocator)
        .then(function (response) {
          vm.newLocator = {};
          $route.reload();
        }, function (error) {
          vm.errorMessage = "Failed to save new item.";
        })
        .finally(function () {
          vm.isBusy = false;
        })
    }
  }
})();

Answer №1

Consider incorporating dynamic parameters into your request:

 $http({
      url: baseUrl + "/" + itemName + "/locators",
      method: "GET",
      cache: false,
      params: {
         r: Math.random().toString(16).substr(2)
      }
    });

If this resolves the issue, explore HTTP Caching policies.
Search for appropriate server-side headers to implement.

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

What is the reason file inputs do not trigger 'input' events, while 'change' events do fire?

Trying out a basic input: <input type="file"/> Noticing that the input event doesn't trigger when a new file is selected: $('input').on('input', function(event){ console.log('input value changed', event.targe ...

What is the correct way to handle BINDing both before and after POPSTATE events when using AJAX?

When dealing with slow AJAX processes, displaying a "loading..." message to the user was deemed beneficial. I have experience using history.pushState and history.popState, but my loading image does not show up when performing actual AJAX requests upon pres ...

Error Unhandled in Node.js Application

I have encountered an issue in my NodeJS application where I have unhandled code in the data layer connecting to the database. I deliberately generate an error in the code but do not catch it. Here is an example: AdminRoleData.prototype.getRoleByRoleId = ...

Rails successfully processed the request with a 200 OK status code, however, the $.ajax() function is triggering the 'error' callback instead of the 'success' callback

In my controller, the ajax request is handled as shown below (simplified): def create ... @answer = Answer.new(video: video_file) if @answer.save render json: @answer.video.url else ... end end This is how I have defined my ajax function: $.aja ...

Deciphering a JSON array by value or key

I have a JSON array that I need to parse in order to display the available locations neatly in a list format. However, I am struggling with where to start. The data should be converted to HTML based on the selected date. In addition, a side bar needs to s ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Error in Webpack: JSX elements that are adjacent must be enclosed within a wrapper tag

After adding a new component and integrating it into my Main component, I encountered an error when running webpack. The error message displayed was: "Adjacent JSX elements must be wrapped in an enclosing tag" Below is the snippet of code where the iss ...

Utilizing PHP to fetch data from a separate webpage

This is a question that has sparked my curiosity. I am not facing any particular issue that requires an immediate solution nor do I possess the knowledge on how to achieve it. I have been contemplating whether it is feasible to utilize PHP for fetching co ...

What are the steps to activate the hot-swapping feature for HTML and JavaScript files in IntelliJ's Community edition?

Just starting out with IntelliJ to work on an AngularJS project with spring-boot as the backend server. Every time I make changes to my HTML or JavaScript code, I find myself needing to restart the app server. Is there a configuration setting or plugin ava ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

A guide to integrating Material-UI with your Meteor/React application

I encountered an issue while trying to implement the LeftNav Menu from the Material-UI example. The error message I received is as follows: While building for web.browser: imports/ui/App.jsx:14:2: /imports/ui/App.jsx: Missing class properties transf ...

The Mongoose findOneAndUpdate method will only return the newly added document when using the $push

Provided here is a structured representation of my "profile" collection: { _id : ObjectId("2bb0fad110"), name : "Tommy", defaultrates : [ {_id : ObjectId("444cbcfd52"), rate : 35.0, raisedOn : "5/2/2009"}, {_ ...

Store the running of a JavaScript file in memory

It seems highly unlikely that achieving the following is possible without expert confirmation: On page number 1, user and application data is requested as soon as the page loads. Page number 2 utilizes the same script, so requesting the same information w ...

Ways to enhance the efficiency of this javascript duplicates

I recently wrote this JavaScript code but, as I am still in the early stages of learning, I am struggling to optimize it efficiently. I ended up duplicating the code for each if statement. $(function() { var lang = $(".lang input[type='checkbox&a ...

Using React js to transform objects into arrays for useState

Hey there! I'm currently working on a webshop demo project for my portfolio. I've encountered an issue while trying to fetch data from commerce.js. The data is in the form of objects, which are causing problems when I try to map them. I've a ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

best practices for passing variables between multiple files within a nodejs application

// script.js var mydata = 1 module.exports = {mydata}; // file in my codebase var newData = require("../script.js") console.log(newData.mydata); // why is it undefined? I want to declare a variable as global across the entire project. I tried using ...

Implementing server-side filtering with Kendo Grid in ASP.NET MVC

I have successfully implemented server-side sorting for my grid using Web Api. Now, I need to add filtering functionality. However, when the grid's datasource sends the filtering arguments to the Web Api controller, the Filter object always appears em ...