What is the best way to send a promise back from my service to my controller?

While I have posed this question in various forms, I now find myself stuck with a piece of code that contains an elusive bug.

My Angular service looks like this:

.service("lookupDataService", [
        '$q', '$http', '$timeout',  function($q, $http, $timeout) {
    this.brokers = function() {
        var cachedBrokers = localStorage.getItem("brokers");

        if (!cachedBrokers) {
          return $http.get('/api/brokers')
                .success(function (data) {
                    localStorage.setItem("brokers", data);
                });
        } else {
            return $timeout(function () {
                return {
                    "data": localStorage.getItem("brokers")
                }
            }, 1000);
        }
    }
}])

I am using this service in my controller

$scope.loadData = function() {
    $scope.promise = $q.all([
        lookupDataService.brokers()
        .then(function(data) { $scope.enquiriesBrokers = data; }),
    ]);
};

There are several issues with the code above, but my main focus is on returning a promise to my controller from the service. Specifically, it seems that $q does nothing with its promise, though it is used later in the code.

While inspecting the data in the service returns the desired results, when it reaches the controller, the data shows as [Object object] instead of an array as expected.

How can I return a promise when none exists?

Below is a snippet of the JSON response received from the service:

And here is an excerpt of the HTML:

<div class="col-sm-4">
    <label for="enquiries-broker">Broker:</label>
    <select ng-model="equiriesSelectedBroker" class="form-control" ng-options="broker.brokerCodeField for broker in enquiriesBrokers" id="enquiries-broker">
        <option value="">Please select a broker</option>
    </select>
</div>

Answer №1

Utilize the $q object and return a promise

.service("lookupDataService", [
    '$q', '$http', '$timeout',  function($q, $http, $timeout) {
this.brokers = function() {
   var defer = $q.defer()

    var cachedBrokers = localStorage.getItem("brokers");

    if (!cachedBrokers) {
          $http.get('/api/brokers')
            .success(function (data) {
                 // resolve the defer
                 defer.resolve({data:data}) 
                localStorage.setItem("brokers", angular.toJson(data));
            });
    } else {
         // resolve the defer
         defer.resolve({data:angular.fromJson(cachedBrokers) })
    }
   // return promise from the defer
   return defer.promise;
  }
 }])

You will consistently receive a promise from the service even without an $http call

EDIT:

Filling in SELECT with JSON so that the ng-model will fetch userIdField

broker.userIdField as broker.brokerCodeField for broker in enquiriesBrokers
specifies to use broker.userIdField as value and broker.brokerCodeField as label

<select ng-model="equiriesSelectedBroker" class="form-control" 
ng-options="broker.userIdField as broker.brokerCodeField for broker in enquiriesBrokers" id="enquiries-broker">
    <option value="">Please select a broker</option>
</select>

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

How can I set a value using document.getElementById(idPopUPImage).innerHTML to create a static popup in Leaflet?

I added a leaflet map to my project which you can find on Codpen In the map, I've included a button key that displays an image in a popup when clicked. However, after closing the popup and reopening it, the image doesn't show unless I click the ...

Confirming user banking information is necessary solely for account activation through Stripe

I've been working with NodeJS and ExpressJS Is there a way to set up account verification with Stripe? I want to confirm that users have bank accounts without charging them. What kind of information can I access through this verification process? My ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

How can I save a Flot chart as a PDF file?

After researching various sources such as a flot issue, a chart comparison, and an answer on Stack Overflow, it seems that exporting a flot chart to PDF may not be fully possible. However, I came across another guideline in this answer suggesting the use o ...

Avoid matching the regular expression

Currently, I am utilizing the regular expression /\s*?left:\s*?-?\d+\.?\d*px;/im to search for instances like: left: 100.5px;. An issue that I am encountering is that it also detects margin-left: 100px; or padding-left.... My obje ...

Using jsPlumb to Access an Element After a "Mouseup" Event has Completed

$(document).on('mouseup', '.agent-wrapper', function(info){ console.log(info); // Everything is working fine console.log(this); }); .agent-wrapper represents an element-wrapper for all jsPlumb objects. $(document).on(' ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

Top solution for preventing text selection and image downloading exclusively on mobile devices

My plan is to use the following code to accomplish a specific goal: -webkit-touch-callout:none; -webkit-user-select:none; -khtml-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none; -webkit-tap-highlight-color:rgba(0,0,0,0); I& ...

Extract branch, path, and URL from the .gitmodules file by utilizing JavaScript Regex

Is there a way to extract branch, path, and URL details from the .gitmodules file using JavaScript Regex? .gitmodules [submodule "PATH"] path = <PATH> url = <URL> [submodule "PATH"] path = <PATH> url = <URL> ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

What could be causing my Vue application to not launch after executing `npm run serve`?

These past 24 hours have been a struggle for me. I recently embarked on the journey of learning Javascript, and my choice of JS framework was Vue JS. However, when I run npm run serve, my Vue JS app bombards me with numerous errors that seem to make no se ...

SheetJS excel-cell customization

I'm using this example to export a worksheet from https://github.com/SheetJS/js-xlsx/issues/817. How can I apply cell styling such as background color, font size, and adjusting the width of cells to fit the data perfectly? I have looked through the do ...

Angular Material - Header Selection Bug

Trying to implement a Select Header is giving me the error message "Error: md-input-container can only have one child input, textarea or select element!" This is the code causing the issue: <md-input-container> <label>Vegetables</l ...

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

Is there a way to include a file in the headers of a POST request and still have standard data in the request body?

Is it possible to attach a file to the header of an existing POST API that is used to send objects to the server? Can a request have multiple content-types? I attempted to use the ngFileUpload directive and provided my object to the data field of the Uplo ...

Retrieve custom content from a database using Laravel and Ajax when clicking on a navigation bar

Recently, I've started working with Laravel 7 and AJAX. One of the features I want to implement is a 'product's name' navbar that displays product details in a div without refreshing the page when clicked. I came across a demo showcasin ...

My desire is for every circle to shift consecutively at various intervals using Javascript

I'm looking to draw circles in a sequential manner. I am trying to create an aimbooster game similar to . Instead of drawing all the circles at once, I want each circle to appear after a few seconds. The circles I've created currently do not g ...

Implementing Security Measures for ExpressJS Static File Server

Recently, I set up an authentication system following a tutorial on express.js and passport.js. In the past, my express server setup used modRewrite as shown below: var express = require('express'); var modRewrite = require('connect-mod ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

The behavior exhibited by node.js express is quite peculiar

I am currently running an Express server. My process involves uploading an Excel File from HTML, which is then parsed by Express to perform calculations. Each row in the Excel file contains information about a User's address. For each address, our ...