While following a tutorial on YouTube, I encountered an issue with incorporating the resolve method getposts
into the contactController. Despite my efforts, no value is being returned.
I've spent hours searching for answers on Stack Overflow to no avail. Can someone please assist me in identifying what I might be doing wrong here?
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>
Issue 1: Removing the two lines of code
controller: "contactController",
controllerAs:"contactCtrl"
and replacing them with
ng-controller="contactController"
in the main div of contact.html
results in an error
Error: [$injector:unpr] Unknown provider: getpostsProvider <- getposts <- contactController
Issue 2: If those controller and controllerAs lines are kept and
ng-controller="contactController"
is removed from the view, then using
$scope to output posts in the view becomes necessary. However, upon executing vm.posts = getposts;
, the JSON response is not displayed in the view. I'm quite confused at this point.