"Exploring the Power of Asynchronous Promises within a Switch Statement in

My current controller setup is as follows:

app.controller('myController', function ($scope, myService) {

    $scope.pageData = {};


    myService.promiseGetDataFromServer()
        .then(function (response) {
        $scope.pageData = response.data;

    }, function (reason) {
       // error has occurred.. etc...
    });
}

While everything is functioning correctly up to this point, I have encountered an issue where I want to populate $scope.pageData based on specific logic. I attempted the following approach:

app.controller('myController', function ($scope, myService2, thing) {

   $scope.pageData = {}

   switch (thing)
   {
       case 'whatever':
         myService2.promiseGetWhateverFromServer()
            .then(function (response) {
            $scope.pageData = response.data;

         }, function (reason) {
           // error has occurred.. etc...
         });
        break;

        case 'something':

          myService2.promiseGetSomethingFromServer()
              .then(function (response) {
              $scope.pageData = response.data;

           }, function (reason) {
              // error has occurred.. etc...
           });
           break;
   }

}

Although there were no server errors and the response was logged successfully, the view did not render as expected. This could be due to the properties of $scope.pageData being undefined.

How can I address this issue? I want the view to render only after the switch statement has executed successfully.

Answer №1

To clarify, you can split the logic by choosing the appropriate service and making the request. Here is an example:

app.controller('myController', function ($scope, myService2, thing) {

   $scope.pageData = {};

  // Selecting the service
  $scope.getDataForPageData = function(parameter){
    var serviceToSelect;

     switch (parameter)
     {
         case 'whatever':
           serviceToSelect = myService1;
          break;

          case 'another':
          serviceToSelect = myService2;
          break;
     }

     return serviceToSelect;

  }

  // Making the request and assigning $scope.pageData when resolved
  $scope.getDataForPageData(thing).promiseGetSomethingFromServer()
        .then(function (response) {
            $scope.pageData = response.data;

        }, function (reason) {
           // Error handling...
        });

}

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 could be the reason for the failure of JSON.parse in parsing the following JSON string: `{ "Search results: ":s"": "" }`?

What could be causing the failure of JSON.parse to parse the JSON string provided below? Is the JSON syntax incorrect? Interestingly, even though its custom JSON parser throws the same error as JSON.parse, https://jsonlint.com/ validates this string. JS ...

Retrieve the JSON data from an AJAX request

I am a beginner in the world of AJAX and JavaScript. In one of my projects, I need to retrieve a JSON object in my JavaScript file. I have utilized spray-json library which displays the JSON object at this URL: http://localhost:8081/all-modules { "statu ...

activating the button once all fields have been completed

Currently, I am utilizing knockout.js for data binding. There is a form with fields for name, number, email, etc. If any of these fields are left blank and the save button is clicked, the button becomes disabled as expected. However, if I later fill in th ...

A guide on setting the array value on the user interface based on a key within the SectionList

My code is currently retrieving an array value and populating these values based on the key in a SectionList. The keys are displaying properly in the UI, but I am encountering some issues in my render item function, particularly in the second section. Esse ...

React hitting recursion limit due to excessive shouldComponentUpdate checks

I'm currently developing a real-time updating dashboard using React. The data for the dashboard components is fetched via an Ajax call and then passed to each component successfully. However, I encountered an issue with one specific component that re ...

Defaulting summernote to display in italics

Looking for a way to italicize a series of summernote inputs by default? I have removed all toolbar options except the italics button. Here's the HTML generating these inputs: <div style="width:250px;"> < ...

turn on labels for every individual cell in the bar graph

I'm working on setting labels of A, B, and C for each bar chart cell to display all my data on the chart. I attempted using data.addColumn('string', 'Alphabets'); but it's not functioning as expected. It seems like a simple ta ...

Is it possible to transform JSON Array Data from one format to another?

As someone who is new to the software field, I am working with a JSON array of objects: var treeObj = [ { "name": "sriram", "refernce_id": "SAN001", "sponer_id": "SAN000" }, { "name": "neeraja", "r ...

What could be causing the service method in the controller not to be called by Node JS?

In my current Node JS project, the folder structure of my app is as follows: src │ index.js # Main entry point for application └───config # Contains application environment variables and secrets └───controllers # Hou ...

Error: No schema found for the specified "User" model

Attempting to establish a connection with the MongoDB database using Mongoose and defining the model resulted in the following error message: MissingSchemaError: Schema hasn't been registered for model "User" Several approaches were taken to address ...

Utilizing Javascript to maintain an ongoing sum within a <span> tag

I'm working on a code snippet to create a running total feature. Essentially, every time a user clicks a button to add the subtotal to the total, I want it to keep accumulating in the running total. Currently, the setup involves a dropdown menu with t ...

The appearance of the webkit-scrollbar is not reflecting the intended style

I have successfully created a wrapper for a styled scrollbar in React JS - import styled from '@emotion/styled'; export const ScrollbarWrapper = styled.div(() => ({ maxHeight: '65vh', overflowY: 'auto', '*::-web ...

The malfunctioning jQuery dropdown menu on hover that needs fixing

Currently, I have an HTML link that utilizes the hover() function (specifically using the hoverIntent plugin) to prompt a div to slide down by animating the CSS top attribute. Everything is functioning as expected, except when the cursor transitions from ...

The input field is not functioning properly within the vue-drag-resize component

I have incorporated vue-drag-resize from https://github.com/kirillmurashov/vue-drag-resize in my project. Unfortunately, I am facing an issue where I am unable to focus and type anything inside an input text field that is contained within the vue-drag-res ...

The Autocomplete feature in Material UI React includes both a "Select All" and a "Select

How can I add Select All and Select None buttons to an Autocomplete component in Material UI React? The goal is for all the options to be checked when Select All is clicked, and for all options to be unchecked when Select None is clicked. <Autocomple ...

Interactive table with dynamic data retrieval

I need help displaying data dynamically from a datatable using an API. The API I am working with is located at this URL and I am utilizing the bootstrap4 datatable. You can also find my code on this JSFiddle. Can someone provide guidance or an example on h ...

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

React - Can you explain the purpose of the callback function in the forceUpdate method?

The React documentation mentions that the forceUpdate method includes a parameter called callback. Does this function in any way resemble the second parameter found in setState, which is executed after setting state? Or does it serve a different purpose? ...

Harnessing JavaScript templates within PHPHow to integrate JavaScript templates

I am currently working on a PHP document where I incorporate 'chapters' (jQuery tabs) in two different ways: Whenever a new chapter is generated, it gets added to the list as well as to the database using JavaScript and Ajax. I have already i ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...