Been spinning in circles on this and would appreciate any help. Trying to pull data from api in service into my controller and repeat the returned data in an ng-repeat.
Have tried to approaches with mixed results.
Approach 1:
Factory
app.factory('getServiceData',function($http){
var getPosts = function(){
return $http.get("http://localhost:3000/posts")
.then(function(response){
console.log(response.data)
return response.data
})
}
Controller
app.controller('myCtrl',['getServiceData','$scope','$http',
function($scope,$http,getServiceData){
getServiceData.getPosts().then(function(data){
$scope.posts = data;
}).catch(function(){
$scope.error ='unable to get posts';
});
My console returns "Provider 'getServiceData' must return a value from $get factory method." So my promise isn't returning a get value that I can use, but not sure how to refactor.
Approach 2 is using resolve on the ngRoutes to pull the api data before the user navigates to the page
Approach 2:
app.factory('getServiceData',function($http){
return {
var getPosts = function(){
return $http.get("http://localhost:3000/posts")
.then(function(response){
console.log(response.data)
return response.data
})
}
};
Config:
.when('/home.html', {
templateUrl: 'app/home.html',
controller: 'myCtrl',
resolve: {
'ServiceData': function(getServiceData){
return getServiceData.getPosts();
}
}
})
The second approach will return the data from my api on the console.log response but I am unable to display it within my controller.