Why resolve method is not returning any data to the controller?

Issue

I was following this tutorial from youtube and was trying to get the resolve method getposts into the contactController. I don’t know why its not return any value.

Could someone tell me whats wrong i’m doing here. I had spent like an hour for this in stackoverflow, but no hopes 🙁

var app = angular.module('simpleApp', ['ngRoute', 'ngSanitize']);

app.config(['$routeProvider', function($routeProvider){
  $routeProvider
  .when('/', {
    templateUrl: './partials/home.html'
  })
  .when('/contact', {
    controller: "contactController",
    controllerAs: "contactCtrl",
    templateUrl: './partials/contact.html',
    resolve:{
      getposts: function($http) {
        return $http.get('https://jsonplaceholder.typicode.com/comments/1')
                    .then(function(response) {
                      // console.log(response.data) returns api data
                        return response.data;
        })
      } 
    }
  }).controller('contactController', ['$scope', '$http', function($scope, $http, getposts){

  vm = this;

  console.log(getposts); // not getting response.data from getposts

  vm.posts = getposts;

}])

// contact.html
<div>
  <div class="row">
    dfgdfg
    <div class="col-lg-6">
      {{ posts }}
    </div>
  </div>
</div>

Problem 1: If i remove the two lines

controller: "contactController",
controllerAs:"contactCtrl"

and add ng-controller="contactController" in main div in contact.html i get an error

Error: [$injector:unpr] Unknown provider: getpostsProvider <- getposts <- contactController

Problem 2: if those controller and controllerAs lines are added and ng-controller="contactController" removed from view then i need to add
$scope to output posts to the view. If i do vm.posts = getposts; its not displaying json response in the view. Oh damn i’m confused.

Solution

Basically you missed to inject getPosts inside inline array annotation of controller DI array.

controller('contactController', [
   '$scope', '$http', 'getposts', //<-- you missed to inject here
      function($scope, $http, getposts){

Answered By – Pankaj Parkar

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.