AngularJS ui-router resolve function may not successfully return a custom value

While attempting to preprocess some data before navigating to my page, I am forcefully resolving a promise, converting it into a custom object, and then trying to return the custom object to my resolve object.

            .state("trip.detail", {
                url: '/:tripId',
                templateUrl: 'partials/trip/detail.html',
                controller: 'TripDetailController',
                resolve: {
                    trainData: function (TripService, $stateParams, $q) {
                        return TripService.getTripById($stateParams.tripId,function (data) {
                            console.log("received: " + data);
                            return {
                                "relativeTrainId": data.trainId,
                                "from": new Date(data.departure).toISOString(),
                                "to": new Date(data.arrival).toISOString(),
                                "projectId": data.projectId,
                                "isTrip": true,
                                "tripId": data.id,
                                "trajectory": data.trajectory,
                                "statistics": data.statistics
                            }
                        }).$promise;
                    }
                }
            });

Everything seems to work fine, except that the 'trainData' being injected into my controller is actually the original 'data' object and not the custom one that I created.

Any idea what might be causing this issue?

Additional information about TripService:

services.factory('TripService', function ($resource) {

function TripService() {
    this.tripResource = $resource('rest/trip/:tripId');
}


TripService.prototype.getTrips = function (start, end, project, trainIds, callback) {
    return this.tripsResource.query({
        projectId: project,
        trainIds: trainIds,
        from: start,
        to: end
    }, callback)
}

TripService.prototype.getTripById = function (tripId, callback) {
    return this.tripResource.get({
        tripId: tripId
    }, callback);
}

return new TripService();

});

Answer №1

To successfully handle data retrieval in your AngularJS application, you need to utilize promises. One approach is to create a custom promise and resolve it with the relevant data:

        .state("trip.detail", {
            url: '/:tripId',
            templateUrl: 'partials/trip/detail.html',
            controller: 'TripDetailController',
            resolve: {
                trainData: function (TripService, $stateParams, $q) {
                    var deferred = $q.defer();
                    TripService.getTripById($stateParams.tripId,function (data) {
                        console.log("Data received: " + data);
                        deferred.resolve({
                            "relativeTrainId": data.trainId,
                            "from": new Date(data.departure).toISOString(),
                            "to": new Date(data.arrival).toISOString(),
                            "projectId": data.projectId,
                            "isTrip": true,
                            "tripId": data.id,
                            "trajectory": data.trajectory,
                            "statistics": data.statistics
                        });
                    });
                    return deferred.promise;
                }
            }
        });

Answer №2

@alfrescian

Your answer was nearly spot-on. I made the adjustment from deferred.$promise to deferred.promise

Appreciate it

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 discord.js to add a reaction to a specific message based on its ID

Is there a method to append a reaction to a specific message using its ID in JavaScript, like messageID.react(' ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

Troubleshooting the issues with implementing cross-browser jscrollpane functionality

Hey there! I've been exploring this tool to customize the default scroll-bar, and here's a fiddle showcasing my experimentation. In the fiddle, I've included the following code snippet <div class="scroll-pane horizontal-only">(located ...

Learn how to show the current page number using React Js with the help of material-ui's

Take a look at the code snippet below from my App.js Component: const App = () => { const [workstations, setWorkstations] = useState([]); let [page, setPage] = useState(1); const PER_PAGE = 1; useEffect(() => { loadWorkstations(); }, [] ...

Node.js tutorial: Matching aggregations by UserId

I have been developing a sample application in React where I have utilized aggregations. One of the functionalities involves implementing a query based on user ID that matches the status and retrieves the MAXDate and MINDate fields. How can I retrieve the ...

Traverse an array in JavaScript using jQuery, PHP, and AJAX

Trying to iterate through a JavaScript object using AJAX has led me to explore options like json_decode, but it turns out this is an array and not an object. var array = [{type: 'a', value: 1}, {type: 'b', value: 1}] $.ajax{ url: "p ...

Does an async function get automatically awaited if called in a constructor?

I am currently working on updating some code due to a library upgrade that requires it to be made async. The code in question has a base class that is inherited by other classes, and I need to call some functions in the constructor that are now asynchronou ...

What is the syntax for implementing a nested for loop in JavaScript within this particular scenario?

var entries = [ { "item": "something", "steps": [{ "node": {"name": "test0"}, "status": {"name": "test"}, "time": {"name": "test"} },{ "node": {"name": "test1"}, ...

Fixing a scrolling element within a div located below the screen is my goal, ensuring it remains fixed in place as the user scrolls

I'm facing a challenge that I need help with: My HTML/CSS layout currently looks like this: Screenshot of how my CSS/HTML appears on the screen upon page load: As I scroll down, I encounter a green element: While scrolling down -> Upon further s ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

Develop an ng-table that includes a dropdown menu allowing users to select the desired amount

I am looking to implement a dynamic ng-table with pagination, but I want the option to change the number of counts per page using a select box instead of buttons. Any suggestions on how to achieve this? Thank you in advance! ...

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

Is there a way to send a Razor boolean variable to an Angular directive?

Within my cshtml file, I am working with a boolean variable. However, when attempting to pass this variable to my Angular directive, it is being received as "False" rather than "false". Even hardcoding it to be "false" in lowercase does not solve the issue ...

Why do style assignments lose their motion when executed right after being made?

If you take a look at this specific fiddle in Webkit, you will see exactly what I am referring to. Is there a way to define the style of an element when it is first specified, and then its final state? I would like to be able to fully define a single-ste ...

A tutorial on how to create the appearance of disabled buttons that look the same as enabled buttons through the use

My button includes a text field that is constantly disabled. I would like for the text field to appear as bright as it does when the button is enabled. After disabling the button, they both appear dimmer compared to others and the text field follows suit ...

Tips on merging HTML node lists from various `getElement`s

Is there a way to combine HTML elements and extract values using array methods? I am struggling to merge them as a nodeList. I tried using get elements and array.unshift to consolidate elements into one variable. var elemsLabel = document.querySelecto ...

Utilizing React Hook to fetch initial data in useEffect

Encountered a roadblock while attempting to update a hook when the web socket is triggered with new data. I noticed that the hooks are returning the default values I initialized them with inside my useEffect, whereas during rendering it shows the correct v ...

The functionality of Nodejs exec is malfunctioning

I need assistance with executing DOS commands using the exec function: java -jar D:\selenium\selenium-server-standalone-2.40.0.jar -htmlSuite "*firefox3 C:\Users\AppData\Local\Mozilla Firefox\firefox.exe" "http://google. ...

Utilizing JSON Data for Dynamically Displaying Database Objects on a Google Map

After carefully reviewing the information provided in the initial responses and working on implementation, I am updating this question. I am currently utilizing the Google Maps API to incorporate a map into my Ruby on Rails website. Within my markets mode ...

When attempting to transfer data to a CSV file from my Firebase database, I encounter an issue where the

I am facing an issue with exporting data from my Firebase Firestore to a .csv file. I have followed all the necessary steps, but whenever I try to add the values for export, they show up as undefined. While I am not an expert in React and consider myself ...