How to inject data into a service without using resolve

My goal is to retrieve data from a server and transfer it to a service before the completion of a route change:

when(
  '/detail/:id', 
  {
    templateUrl: './partials/views/detail.php',
    controller: 'detailCtrl',
    resolve: {
      init: function($route,$q,shipmentn){
        var deffered = $q.defer();

        shipmentn.getSingle($route.current.params.id).then(function(promise){
          shipmentn.data = promise.data;
          deffered.resolve(promise);
        });

        return deffered.promise;
      }
    }
  }
)

It's worth noting that I've placed this logic inside the then() function to ensure the request is complete.

However, I find it frustrating that I need to inject an additional dependency (init) into my controller and return a promise that is not utilized.

Is there a way for me to work around this issue?

Answer №1

One strategy you could use is to provide the required service to the resolve function of a deferred object in your controller after the service has loaded:

when('/detail/:id', {
  templateUrl: './partials/views/detail.php',   
  controller: function($scope,service){}, //<-- Controller with the service dependency
  resolve: {
    service: function($route,$q,shipmentn){
      var deffered = $q.defer();       
      shipmentn.getSingle($route.current.params.id).then(function(promise){
        shipmentn.data = promise.data;
        deffered.resolve(shipmentn); //<-- the deffered resolves the service
      });
      return deffered.promise;
    }
}})

Best regards,

Answer №2

In order to simply send data to the controller without storing it in the service, you can directly resolve it to the controller:

router:

when('/detail/:id', {templateUrl: './partials/views/detail.php',   controller: 'detailCtrl',resolve: {

            shipmentData: function($route,$q,shipmentn){
                return shipmentn.getSingle($route.current.params.id));
            }

        }})

service:

getSingle: function(id){
 var deferred = q.defer();

 $http.get(...).then(function(response){
  deferred.resolve(response.data);
 }

 return deferred.promise;
}

controller:

module.controller('detailController', ['shipmentData', function(shipmentData){
 ...
}]);

When accessing the controller, shipmentData will contain the data returned from response.data through http.get.

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

Using jQuery to add and remove CSS classes on IE9 with Selenium

Hello, sorry for the generic question. We are currently automating our UI testing using Selenium Web Driver (v2.24.1) and everything is going smoothly except for IE9. One of the functionalities we are testing involves showing and hiding UI controls using ...

Finding and retrieving the checked checkboxes in Selenium WebDriver without using the name or xpath

Can you help me figure out how to identify the selected checkbox from a list of checkboxes when no name or xpath is provided? Here is an image of the checkbox: enter image description here This is the HTML code generated: <div class="c ...

When using ngOptions, remember that ngModel can be set to an entire object, not just its value

I am struggling to set my ng-model to hold the value of the select instead of the entire object. HTML <select name="status" data-ng-model="search.status" data-ng-options="s.label for s in statuses"> </select> $scope.statuses ...

Swapping out a partial for a form partial using ajax upon clicking the edit button

I am working on a Rails application and I'm looking to implement a functionality where clicking "edit" will replace a show partial with a form partial. To achieve this, I have started integrating Ajax and jQuery by including remote:true in my edit li ...

Is it possible to display an HTML file along with accompanying JS files using Express in Node.js?

I am working with an index.html file and I need to send it using the following Node.js code: app.get('/', (req, res) => { res.sendFile(`${__dirname}/index.html`) }); Within the same directory, I also have some JavaScript files that I want ...

Apologies, there seems to be a problem: TypeError - Unable to access the property 'map' as it is undefined

Just dipping my toes into reactjs by following a tutorial. However, it seems like the tutorial is slightly outdated because I keep encountering this error message: Uncaught TypeError: Cannot read property 'map' of undefined at ContactsList.r ...

"What might be causing the error 'cannot access property 'top' of undefined' while trying to read

My website has a sticky navbar fixed at the top, and this is the structure of my sticky navbar: $(function() { $(window).scroll(function() { if ($(window).scrollTop() > $(".b").offset().top + $(".b").height() && $("input").val() == "") { ...

Why is it that my website in React crashes when I type rapidly in the TextField component?

Whenever I input text quickly into the TextField in my app, it causes my website to crash and display a blank white screen. Below is the snippet of code causing the problem: TextField Code: <TextField label="Item name" ...

What could be causing the lack of change in direction for the initial function call?

There appears to be an issue with image(0) and image(1) in this array that I can't quite understand. The console output shows: i=5; div class="five" id="slides" i=0; div class="one" id="slides" i=1; div class= ...

How to retrieve a specific item from an array in JavaScript

I am retrieving this list from the server using PHP: ["Ak-Bulak","Balykchy","Batken"] How can I access it and insert it into select options using JavaScript? Here is what I have tried so far: for (var i in data) { $('#cities').append(' ...

Display the Bootstrap modal only once after a specific portion of the page has been scrolled upon initial

I've almost got this feature working, but I think I'm missing some key logic. My goal is to have a Bootstrap modal appear when a user scrolls to 70% down the page. It's working, but the issue is that when I close the modal, it immediately re ...

Error in Angular timer causing NaN result

Struggling to create a timer in JavaScript, a basic one at that. I wrote what I thought was correct code, but it's not functioning properly - resulting in the textbox value changing to NaN after just one second. Below is the code snippet: <timer ...

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

Accessing the req object in Node.js using Express

Currently, I am attempting to redefine the function send in order to include an express-session value with each response. Unfortunately, I seem to be encountering issues accessing the variable req within the definition of send. 01| let app = express(); 02| ...

What is causing this code to malfunction?

Currently delving into the world of Ajax, I've been following a tutorial and have crafted the script below: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function MyFunction(){ var xmlhttp; if(windo ...

Is there a way to show both miles-per-hour and kilometers per hour side by side

Is it possible to display both miles per hour and kilometers per hour together? How can I incorporate the calculation for kilometers per hour and showcase it alongside miles per hour? function getMiles (knots) { var mph = (knots * 1.15078); va ...

Invalid data returned in AngularJS $http request

Just diving into angular js and I'm trying to send a URL to the server. Here's my code: Index.html <html ng-app="signupApp"> <head> <title>ServicePrice Signup</title> <link rel="stylesheet" href="c ...

Discovering DOM elements positioned between two other well-established DOM elements can be achieved by utilizing a variety of methods

What is the most efficient and elegant way to select all elements between two specified elements using vanilla JavaScript? For instance, how can I target all elements between: <h2> and <hr> .. and the result should be an [ p, p, ul ] ... but & ...

What is a suitable alternative to forkJoin for executing parallel requests that can still complete even if one of them fails?

Is there a more robust method than forkJoin to run multiple requests in parallel and handle failed subscriptions without cancelling the rest? I need a solution that allows all requests to complete even if one fails. Here's a scenario: const posts = th ...

Retrieve the HTML element by providing its specific index within the DOM structure of the document

I am working with the HTML source of a document stored as a string and have the index i which indicates where an element starts within this string. I am looking to create a function called getElementByIndex(i) that will return the appropriate JavaScript D ...