Search code examples
javascriptangularjsserviceionic-frameworkfactories

Multiple services in Ionic - how to structure multiple services in one file?


I have a question about Ionic services. As you know, Ionic framework comes with a built in www directory which contains the js directory, which contains the services.js file. My first service works. I attempted to write another service in the same, services.js file and as it turns out, I got an error: Uncaught "SyntaxError: Unexpected token . http://localhost:8100/js/services.js Line: 57" in addition to "(index):28 Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to: Error: [$injector:modulerr] Failed to instantiate module starter.services due to: Error: [$injector:nomod] Module 'starter.services' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument." Anyway, here's my code, take a look and let me know what I can do differently. Also, if you need more snippets, let me know!

//services.js 
//the first factory, API works 
angular.module('starter.services', [])
.factory('API', function($http) {
    var apiFooUrl = 'http://localhost:3000/api/do/thing'
    return {
        all: function(){
              return $http.get(apiFooUrl + 's')
        },

        show: function(thingID){
              console.log("stock service get running", thingID);
              return $http.get(apiFooUrl + '/' + thingID)
        }
  };
});
//this is the one that returns the error
.factory('Users', function($http) {
    var apiUrl = 'http://localhost:3000/api/users/'

    return {

        index: function(){
          return $http.get(apiUrl)
        }

        show: function(id){
          return $http.get(apiUrl + id)
   }
  }
})

Edited for more info: So in response to David L's comment: I've injected it into my GlobalCtrl like so:

.controller('GlobalCtrl', function(Users, $rootScope, $state, $window,   
Things, $scope){
      $scope.newUser = {}
      $scope.user = {}

      //show all Users
      Users.index().success(function(results){
       $scope.users = results
      })
})

It'll also be injected into a DetailCtrl as well. In app.js, the services are injected like so:

angular.module('starter', ['ionic', 'starter.controllers', 
'starter.services'])

There's a lot more that needs to go on eventually so I want to make sure I have it right, now.

Have I included the starter.controllers properly? Do I have to include more than one if I have multiples? They are indeed included in the index.html file.


Solution

  • you have added service after closing the module, removing the semicolon will solve this problem

    }) //here reomved the semicolon
    //this is the one that returns the error
    .factory('Users', function($http) {