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

Issues related to validation prior to submission

Having trouble with a VeeValidate example from the documentation. The example can be found here. I seem to be missing something crucial but can't figure out what it is. For some reason, my form always validates as valid, even when no text is entered ...

Conceal div elements and retain their status when the page is reloaded or switched

I currently have 3 div elements displayed on a webpage: header-div fixed_menu_div page_cont Each of these divs are styled with the following CSS properties: #header-div { top:0; left:0; display:inline; float:left; } #page_cont { mar ...

Using Laravel to remove data with an incorrect ID

Whenever I try to delete data using the Delete button, it seems like the data being deleted does not correspond to the rows I intended. Instead, the data at the top of the table gets deleted. For example, when I use return $meja, id 1 shows up instead of ...

Seems like the ng-show events inside are not being triggered, almost like an invisible image

I am encountering an issue where no JavaScript events are triggering inside an ng-show div in my code. You can access my code through the following link on Plnkr: http://plnkr.co/edit/kGqk8x?p=preview Upon loading data from JSON, I set ng-show to true. Ho ...

Updating a calendar page in Rails 4 using AJAX technology

Currently, I am utilizing jQuery's datepicker functionality to display a calendar. The intended behavior is that upon clicking on a specific date, the page should generate relevant information (in this case, a table showcasing available seating) assoc ...

Encountering JSON error when invoking multiple functions

Encountering JSON Error when calling multiple functions Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0 I've been attempting to call multiple functions in jQuery but keep getting an error. I've tried various soluti ...

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

Unable to switch the text option

[Fiddle] I'm currently working on a project where I want pairs of buttons to toggle text by matching data attributes. While I can successfully change the text from "Add" to "Remove" on click, I am facing an issue with toggling it back to "Add" on the ...

Is it advisable to modify the value of props by using toRef in the Composition API?

I've noticed a common practice in the CompositionAPI where props are converted to refs using `toRefs` function. This has left me feeling a bit confused. For instance, citing the Vue 3 official guide: export default { props: { user: { type ...

Is there a way to route an angular request through a spring filter prior to validation?

I'm currently working on implementing an XSS Filter in a backend application (built with JAVA and Spring). The goal is to validate input values from a frontend app (AngularJS) against the filter before proceeding to validate the rest of the content. ...

Chrome extension for AJAX with CORS plugin

Currently, I am utilizing jQuery for cross-origin AJAX requests and attempting to include headers in the request as shown below. However, I am encountering an error message stating that it is an invalid request: $.ajax({ url: address, headers:{ ...

What is the best method for effectively eliminating duplicate objects with the same value from an array?

Let's say we have a collection of jqlite objects, and using the angular.equals function, we can determine if they are equal. How can we utilize this function to eliminate duplicate items from an array of jQlite objects? This is my attempted solution: ...

Adjust the jQuery.ScrollTo plugin to smoothly scroll an element to the middle of the page both vertically and horizontally, or towards the center as much as possible

Visit this link for more information Have you noticed that when scrolling to an element positioned to the left of your current scroll position, only half of the element is visible? It would be ideal if the entire element could be visible and even centere ...

Concealing and revealing the triangular indicator within a bullet diagram using the AngularJS-nvd3-directives library

I am currently utilizing the nvd3-bullet-chart feature from the angularjs-nvd3-directives library in order to present maximum, current, and average data. To exclude the minimum variable from the array for display purposes, I have set its value to 0. In a ...

The correct organization of angular files

Seeking advice on the optimal angular file structure for my upcoming project. It will be a single page application featuring a video feed on the main page, as well as specific post viewing pages. The goal is to provide users with login capabilities, conten ...

Angular binding causing decimal inaccuracies

Within my $scope, I have a variable tobing that can be either 2.00 or 2.20, and I am binding it to: <span>{{datasource.tobind}}</span> I want the displayed text to always show "2.00" or "2.20" with the two last digits, but Angular seems to au ...

Limiting Velocity in a Two-Dimensional Spacecraft

Like many others diving into the world of programming, I decided to challenge myself with a spaceship game project. At this point, I have successfully incorporated parallax stars and other essential features expected in a space-themed game. The spacecraft ...

To style the input box, apply the CSS properties "filter: alpha(opacity=70);" and "background-image: url(image.png);"

Individual functionality for both the form and css has been achieved, but when trying to implement them together, they do not work as intended. This integration is specifically for a windows sidebar gadget. Here is the structure of the form: <form nam ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...