Injecting resolve into Angular controller and encountering undefined value in logging operation

My setup involves the following:

.state('posts', {
      url: '/posts/{id}',
      templateUrl: 'posts.html',
      controller: 'postsController as postsCtrl',
      resolve: {
        post: getSinglePostWrapper
      }
    })

I also have a helper function:

getSinglePostWrapper.$inject = ['postsService', '$stateParams'];
function getSinglePostWrapper(postsService, $stateParams) {
    return postsService.getSinglePost($stateParams.id);
}

The controller code is as follows:

angular.module('flapperNews')
.controller('postsController', postsController);

postsController.$inject = ['postsService', 'post'];

function postsController(postsService, post) { 
   var vm = this;
   vm.post = post;
   console.log(post); //undefined here
}

When attempting to inject the post from the resolve, I'm encountering an issue where "post" becomes undefined. However, logging the post in the getSinglePostWrapper function shows the correct object. It seems like there may be a loss of binding between the resolve and the controller.

Here's the posts service:

angular.module('flapperNews')
.factory('postsService', postsService);

postsService.$inject = ['httpService'];

function postsService(httpService) {
  return {
        getSinglePost: getSinglePost
  }
  function getSinglePost(postId) {
        httpService.baseGet('/posts/' + postId)
        .then(function(data) {
            return data;
        }, function(data) {});
  }
}

And here's the http service:

angular.module('httpService', [])
.factory('httpService', httpService);

httpService.$inject = ['$http', '$q'];

function httpService($http, $q) {
  return {
        baseGet: baseGet
  }
  function baseGet(url) {
        return $http.get(url).then(
                function (result) {
                    return result.data;
                },
                function (result) {
                    return $q.reject(result);
                }
        );
    }

}

Additionally, I've injected httpservice into the initial declaration of the flapperNews module.

Everything is functioning correctly with other HTTP requests, but the injection of the post into the controller is not working as expected.

Answer №1

The promise sequence stops here.

  function fetchPost(postId) {
        httpService.get('/posts/' + postId)
        .then(function(data) {
            return data;
        }, function(data) {});
  }

If you do not return the promise, the variable post will be resolved as undefined before the completion of the httpService.get request.

Answer №2

Give this a shot:

.state('articles', {
      url: '/articles/{id}',
      templateUrl: 'articles.html',
      controller: 'articlesController as articlesCtrl',
      resolve: {
        articleData: function('articlesService', '$stateParams') {
           return articlesService.getSingleArticle($stateParams.id);
      }
    })

angular.module('newsApp')
.controller('articlesController', function($scope, articleData){
    $scope.article = articleData;
   console.log($scope.article); //should display the article object
});

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

Is it appropriate to include a function within a loop?

I'm curious to know if it's considered good practice to call a function inside a loop. Both of the following code snippets produce the same result, but I want to add clarity by using a function. Is this considered good practice? Thank you. Code ...

Verify if data is correct before refreshing user interface

When attempting to submit the HTML5 form, it stops the form submission if any required fields are missing a value or if there is another error such as type or length mismatch. The user interface then shows highlighted invalid fields and focuses on the firs ...

Mastering the use of npm and sails to create HTML-PDF files effortlessly

UPDATE: I am simplifying my question and will address any other concerns in separate posts if necessary. The initial post was too lengthy, hoping for a straightforward guide on utilizing sails to its fullest potential. Apologies. To begin with, my knowled ...

When additional lines are drawn elsewhere on the HTML5 Canvas, the diagonal lines will gradually appear thicker and more pronounced

For horizontal and vertical lines, using a translation of 0.5 for odd stroke widths results in crisper and sharper lines. But what about diagonal lines? Link to jsfiddle <!DOCTYPE html> <html lang="en"> <body style="background: black"& ...

Guide to importing multiple controllers using express

For my upcoming full stack project, I am working on various controllers like signup, login, and profile. Instead of manually requiring each controller and adding them to the app using individual lines of code, I am seeking a more efficient solution. I env ...

A div element with the class name "draggable" is

One of my functions sends notifications to a page by prepending a main div with the notification. Here is the function: function displayNotification(notificationTitle, notificationContent, notificationColor, notificationSize) { console.log('Attem ...

Display hyperlinks upon hovering over text

In the sign-up form, there are options for two different types of users: teachers and students. When the sign-up option is selected, a drop-down menu with choices for teacher and student will appear. However, I would like it to function more like other w ...

Trouble with Mongoose save() function failing to update data

I am currently working on enhancing a fully functioning CRUD app by adding a new feature that allows users to update a list of vendors. They have the ability to add new vendors, update existing ones, and delete vendors. While the add and delete functions a ...

Determine which checkbox is currently selected in Vue and send corresponding data based on the checked status

A radio form that is conditionally disabled by another checkbox. One radio button can send either true or false and the other has an input that sends some data. How can I determine which radio button is checked and decide whether to send true/false or the ...

Issue with `npm run watch` failing to compile when the data source is turned

Currently, I am faced with a challenge while working on Laravel and utilizing various node packages for development. The issue at hand is my limited internet connectivity. Every time I attempt to execute npm run watch, it refuses to initiate unless I am c ...

Automatically initiate a click event when the page is loaded

I'm having trouble getting a click event to trigger on my controller when the page loads. I really just want the checkboxes to be clicked automatically. <!DOCTYPE html> <html > <head> <link rel="stylesheet" type="text/css" ...

What could be causing this JS file to not impact the DOM as expected?

Currently, I am delving into the world of JavaScript and trying to gain a better understanding of how to manipulate the DOM on my own. Throughout this learning process, I have encountered a puzzling situation that I am seeking assistance with. The followi ...

Transfer JSON data between controllers without utilizing Services or Factory in AngularJS during routing

On my Dashboard page, I have an Object. When a user clicks on the Details Page from the Dashboard, it should redirect to the Details page. I am looking to pass the JSON Object from the Dashboard Controller to the Details Controller. Is there a way to do ...

Adding page numbers in a select dropdown menu without using the traditional next and previous buttons

I am attempting to implement a select tag paging feature using the code below: <select ng-change="params.page(page)" ng-model="page" ng-options="page.number as page.number for page in pages"></select> However, I noticed that when I incorporat ...

Using Javascript to Retrieve Object-Related Information from an Associative Array

I have a list of students' names along with the grades they achieved for the semester. How can I modify my JavaScript code to display the first names of students who earned an "A" grade based on the array provided? This is my current progress, but I k ...

Ways to retrieve parameters in getStaticPaths function?

I'm currently working on a Next.js app with Contentful as the CMS. The file structure relevant to my question is: pages -[category] -[slug].js My goal is to access the category value when a user visits category/slug. Currently, I have the category ...

Angular Single Page Application Development

Currently exploring the implementation of a single-page application in Angular.js Came across a helpful demo at http://scotch.io/demos/angular-single-page-routing which seems suitable for my needs. However, while browsing through http://scotch.io/demos ...

Redux's 'connect' function fails to recognize changes in the state array

I've recently implemented redux with a reducer that handles an array of time slots for a specific date. Whenever the date is changed, the reducer successfully updates the state (confirmed through console logs in my mapStateToProps function). However, ...

Leveraging JavaScript event handlers within a progress wizard located within an update panel

I need assistance with implementing a password strength meter for a textbox within a wizard control. The issue I'm facing is that the password box does not become visible until step 4, preventing me from registering an event handler onload(). Placing ...

Ways to store user data in AngularJS

Can anyone provide insights on how to securely save user information? I've heard suggestions like using $cookieStore, or Authentication, among others. What about utilizing $rootScope for this purpose? My thought is to store the user's ID and p ...