0

Below I've got an angular app and controller where the controller have data access inside of it (bad idea, I know)

var app = angular.module('app',[]);
app.controller('HomeController',function($scope,$http){
    $scope.people = null;
    $scope.get = function() {
        $http({
            url: 'largeTestData.json',
            method: 'GET'
        }).then(function(data){
            console.log('request successful, here is your data: ');
            console.log(data['data']);
            $scope.people = data['data'];
        },function(reason){
            console.log('this failed, this is the reason: ');
            console.log(reason);
        })

    }

});
app.controller('ControllerWithService',function($scope, MyService){
    $scope.get = MyService.get;
    $scope.get(function(data){
        console.log('you succeeded');
    },function(reason){
        console.log('you failed');
        console.log(reason);
    })

})

This will work in retrieving data and putting it onto the page. Knowing that having data Access in the controller is no bueno I tried to abstract that out into a service:

app.service('MyService',function($http,$q){
     var get = function(){
         var deferred = $q.defer();
         var url = 'test.json';
         $http.get(url).success(deferred.resolve).error(deferred.reject);
     }
    return {
        get: get
    }
})

Here my 'data layer' is a service that only has one method: get from the above listed URL.

app.service('MyService',function($http,$q){
    var get = function(){
        var deferred = $q.defer();
        var url = 'test.json';
        $http.get(url).success(deferred.resolve).error(deferred.reject);
    }
    return {
        get: get
    }
})

and my HTML

<body>
    <script src="libs/angular-1.2.15.js"></script>
    <script src="app/app.js"></script>
    <script src="app/DocumentService.js"></script>
    <script src="libs/jQuery-2.1.1.js"></script>
    <div ng-controller="HomeController">
        <button ng-click="get()" href="#">Get data</button>
        <div>{{message}}</div>
        <!--<div ng-repeat="p in people" >-->
            <!--<b>Business Doc ID: </b><h1>{{p['busDocId']}}</h1>-->
            <!--<b>DOC ID: </b><a href="#">{{p['docId']}}</a>-->
            <!--<b>FILE NAME: </b><div style="color: green">{{p['fileName']}}</div>-->
        <!--</div>-->

    </div>
    <div  ng-controller="ControllerWithService">
        {{message}}
        <button ng-click="get()">get data</button>
        <div>{{data}}</div>

    </div>

</body>

I'm not getting any error messages, and the commented out out stuff in my HomeController works as expected. What am I doing wrong in trying to make my AJAX calls a service?

working solution changes:

    app.service('MyService',function($http,$q){
        this.get = function(){
            return $http.get('test.json')
        }
    })


app.controller('ControllerWithService',function($scope, MyService){
    $scope.data = null;

    $scope.get = function() {
        MyService.get().then(function (data) {
            console.log('this is the success data: ');
            console.log(data)
            $scope.data = data;
        }, function (reason) {
            console.log('this is the fail reason');
            console.log(reason);
            $scope.data = reason;
        })
    }
})
wootscootinboogie
  • 8,461
  • 33
  • 112
  • 197

1 Answers1

1

It looks like it could be a couple different things. I'll post an example I have working in one of my projects right now. It should be extremely similar and simple with what you're goal is.

Service:

'use strict';
angular.module('srcApp')
  .service('Getlanguage', function Getlanguage($location, $http, $log, $state, $rootScope) {

        this.getContent = function() {
            var language = $location.path().split('/'),
                languageCulture = language[1];

            if (!languageCulture) {
                languageCulture = 'en';
            }

            $rootScope.cultureCode = languageCulture;

            return $http({method: 'GET', url: '/languages/' +  languageCulture + '.json'})
            .error(function() {
                // If service cannot find language json file, redirect to index
                $state.go('lang', {lang: 'en'});
            });
        };


  });

Controller Call to service: After passing in the service as a dependency into the controller.

 Getlanguage.getContent().then(function(res) {
    $scope.content = res.data;
 });

Hope this helps.

Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94
  • Using my promise as a success handler since if the request fails, it will always just redirect to index. Something specific in my case. Adding a success handler should be the same though. – Christopher Marshall May 29 '14 at 21:11
  • do you think that the success/fail callbacks should be in the controller or in the service? I suppose controller if you want the promise to do different things. – wootscootinboogie May 29 '14 at 21:11
  • I think it depends on the context/intent. I have mine right in the service because my whole site content depends on that request. – Christopher Marshall May 29 '14 at 21:13
  • 1
    not sure if you care or not, but if you ever want to minify your scripts, it won't work with angular the way you're using it. http://stackoverflow.com/questions/18782324/angularjs-minify-best-practice for me info. Thanks, I ended up getting this working. – wootscootinboogie May 29 '14 at 21:22