User interface not refreshed following $http.get request

Greetings, I am currently working with an angular.js controller that looks like this.

function WorkSpacesController($scope, $http, notifications) {
  $scope.Workspaces = [];
  $scope.Query = "";
  $http.get("api/Workspaces/GetAllWorkspaces/").then(function(response) {
      for (var i = 0; i < response.data.length; i++) {
          $scope.Workspaces.push(response.data[i]);
          notifications.showSuccess("Added new Item");
      }
  },
  function(data) {
      notifications.showError("Could not load workspaces");
  });
}

The notifications.showSuccess and notifications.showError functions are responsible for displaying notifications on the screen. These functions are implemented using https://github.com/alexbeletsky/ng-notifications-bar.

What's interesting is that the showSuccess function works perfectly and displays the notification as expected. However, the showError function does not seem to work at all and nothing is displayed. I have checked the code thoroughly, added messages to the array, and no errors are reported. Just to double-check, I even tried calling showError instead of showSuccess, and surprisingly it worked fine.

Any ideas why the user interface fails to update when showError is called?

Answer №1

It seems like the issue may lie within your notifications service, as the provided example is functioning correctly.

angular.module('app', []).controller('WorkspacesController', function($scope, $http, notifications, $templateCache) {
  $scope.Workspaces = [];
  $scope.Query = "";

  //for demonstration purposes, store a URL in the http cache for easy loading without an actual HTTP request
  //test a successful request
  $http.get('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css').then(function(response) {
      //for (var i = 0; i < response.data.length; i++) {
      //$scope.Workspaces.push(response.data[i]);
      notifications.showSuccess("Added new Item (for good request)");
      //}
    },
    function(data) {
      notifications.showError("Could not load workspaces (for good request)");

    });

  //test a failed request
  $http.get('url_that_does_not_exist').then(function(response) {
      //for (var i = 0; i < response.data.length; i++) {
      //$scope.Workspaces.push(response.data[i]);
      notifications.showSuccess("Added new Item (for bad request)");
      //}
    },
    function(data) {
      notifications.showError("Could not load workspaces (for bad request)");
    });

}).service('notifications', function() {

  return {
    showSuccess: function(message) {
      alert('Success: ' + message);
    },
    showError: function(message) {
      alert('Error: ' + message);
    }
  };
})
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdaca3aab8a1acbfe3a7be8dfce3f8e3fd">[email protected]</a>" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="WorkspacesController as vm">

</body>

</html>

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

Changing background color using jQuery ID selector

Within thisid, the id of an html element is stored. In order to modify its background color, the code below can be utilized: let thisid = 'test'; $("a#" + thisid).css("background-color", "yellow"); <script src="https://cdnjs.cloudflare.com/a ...

Angular directive for dynamic template inclusion

I am facing an issue while creating a directive that should automatically add tabs and their content. The problem I'm encountering is retrieving the content stored in partials/tabs/tab[x].html. In my code, I have defined a constant named AvailableTab ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

Discovering identical values within an array along with the differences between them

For instance: [1, 4, 9, 78, 42, 4, 11, 56] In this scenario, the duplicated number is 4 and the difference is 3. Although I utilized the array for every array element, I aim to enhance this query for better optimization. ...

What are the best practices for handling dynamically generated fields?

I have a web layout with multiple dynamically created links using AJAX functions, and they are functioning correctly. However, I am unsure how to interact with these dynamically generated links. How can I call a JavaScript or jQuery function when I click ...

Working with Angular to Retrieve a File Using Ajax

My dilemma revolves around a service that is capable of generating a CSV file and sending it back to the page through an http/ajax get request. The desired user interaction involves clicking a button, triggering the service call, and initiating the downloa ...

Is it possible for a destructed assignment to yield multiple objects?

I am faced with a collection of Storybook stories and a function that produces a ComponentStory object. I am aiming to find a concise method for duplicating multiple stories without resorting to repetitive code like this: export const Default = bindStory(T ...

FusionCharts Gauges may share similar code, but each one produces a unique output

Currently, I am developing a project that involves creating a dashboard with 3 gauges. These gauges are enclosed in bootstrap cards with a column value set to 4. In the layout of the dashboard, these 3 cards are positioned next to each other. I have succe ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

How do I switch the background-image on li hover and revert it back when I move off the li element?

Looking to update the background image of a div upon hovering over a li element? Check out this example here. So far, I've got that part working fine. But now I want the background picture to revert back to its original CSS when I move away from the l ...

The Child component is unable to render initially due to the Context API being undefined during the first render of the Child component

I'm struggling to ensure that a child component only renders when the Context API state I've set up is fully mounted. The Parent component fetches data from the server and sets the state based on the received information. Initially, I keep gettin ...

Ways to generate a unique random number from an Array without repetition using Javascript

Looking to retrieve a random number from an array of numbers known as cardNumbertemp. function shuffleCard(){ randomized = Math.floor(Math.random()*cardNumbertemp.length); for (var i = 0; i < cardNumbertemp.length; i++){ ...

How can the name of an element be passed as an argument to a function called by that element within a Vue component?

I'm currently developing an interactive SVG map inspired by the one found on the CDC page. In my SVG map component, I have implemented multiple path elements that each contain a unique name attribute representing the corresponding state. Additionally, ...

Navigating in Angular 2 RC4 with Path Variables Containing Special Symbols

Could someone offer suggestions on how to correctly call parameters with special characters from URLs? Below is my current code for calling the parameter: ngOnInit() { this.route.params.subscribe(params => { let accountrefID = params ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

Unusual occurrences when making several ajax requests to a single URL

I've encountered a peculiar scenario while working on a CherryPy server, and I'm seeking assistance in understanding the intricacies behind it. Here's the content of server.py: import cherrypy import os import threading class Root(object): ...

Ways to interpret and contrast the information within files (verifying if the lengths of the strings are identical)

I have a web tool where users can upload text and code files, which are then saved in a local directory. I'm trying to create a function that reads these files, compares their lengths, and generates a report indicating whether they are equal or not. B ...

What is the process for transitioning from Ajax to Fetch API in JavaScript?

Currently, I am utilizing the JavaScript version of RiveScript which relies on ajax, and I have decided to move away from using jQuery. There is a single line of ajax code that I need to update to integrate the new Fetch API. **Note: The ajax code can be ...

Unexpected behavior from Internet Explorer - Span contents remain unchanged despite valid input

I have a simple question because I'm feeling a bit lost. Check out this JSFiddle link It seems that in Internet Explorer, the contents of my span won't update even though the input is valid. However, in other browsers, the span content changes ...

Switch between various height and width options using JavaScript

Is there a way to create a toggle that changes both the height and width of an element when it is clicked? <div class="flexbox-container" id="main" onclick="staybig()">Create Account</div> .flexbox-container { ...