Using Angular JS services and controllers in separate files may result in errors

Within my angularjs project, I manage the following files:

/index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <title></title>

  <link href="lib/ionic/css/ionic.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

  <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
  <link href="css/ionic.app.css" rel="stylesheet">
  -->

  <!-- ionic/angularjs js -->
  <script src="lib/ionic/js/ionic.bundle.js"></script>

  <!-- cordova script (this will be a 404 during development) -->
  <script src="cordova.js"></script>

  <!-- Custom Libraries -->
  <script src="lib/Shake.js"></script>

  <!-- your app's js -->

  <script src="js/services/CloudDatabases.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/app.js"></script>

</head>

<body ng-app="starter">
  <ion-nav-view></ion-nav-view>
</body>
</html>

/js/apps.js

// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' can be found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

    // Register stopping and starting analytics on app open and close
    document.addEventListener("pause", window.analytics.Stop(), false);
    document.addEventListener("resume", window.analytics.Start(), false);

    // Exit the application if you go offline
    document.addEventListener("offline", function(){}, false);
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl: "templates/menu.html",
      controller: 'AppCtrl'
    })

    ....
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/login');
});

/js/services/CloudDatabases.js

angular.module('starter.services')
.service('CloudDatabases', ['$http', function ($http) {

    var urlBase = '/api/customers';

    this.getDatabases = function () {
        console.log('CloudDatabases.getDatabases();');
        return 'test getDatabasesResponse';
    };
}])

/js/controllers.js

angular.module('starter.controllers', ['CloudDatabases'])

// Login controller
.controller('LoginCtrl', function($scope, $ionicLoading, $http, $ionicPopup, $rootScope,     $state, $ionicViewService, CloudDatabases) {
  CloudDatabases.getDatabases();

  // Form data for the login modal
  $scope.loginData = {};

  // Try loading the loing data from storage if the user has already logged in
  $scope.loginData.username = window.localStorage['username'] || '';
  $scope.loginData.password = window.localStorage['password'] || '';
  $scope.loginData.uk = window.localStorage['uk'] || false;

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    // Show the loading overlay so the user knows we are busy
    $ionicLoading.show({template: 'Loading...'});     

    // Save the login data to local storage so if the user closes the app they
    // don't have to re-enter it
    window.localStorage['username'] = $scope.loginData.username;
    window.localStorage['password'] = $scope.loginData.password;
    window.localStorage['uk'] = $scope.loginData.uk;

    // Build login JSON from form
    var login_json = JSON.stringify({auth: {passwordCredentials: {username:     $scope.loginData.username, password: $scope.loginData.password}}});

    // POST the actual authentication request
    $http({
        method: 'POST',
        url: 'https://identity.api.rackspacecloud.com/v2.0/tokens',
        data: login_json,
        headers: {'Content-Type': 'application/json'}
    }).then(function(response) {

      // Save the auth token and tenant id for later use
      $rootScope.userData = [];
      $rootScope.userData.Token = response.data.access.token.id;
      $rootScope.userData.Tenant = response.data.access.token.tenant.id;
      $rootScope.userData.RawServices = response.data.access.serviceCatalog;

      // Use viewservice to hide back button on next page and remove login from nav stack
      $ionicViewService.nextViewOptions({
        disableBack: true
      }); 

      // Track successful logins
      window.analytics.trackFeature("Login.Success");

      $ionicLoading.hide();

      // Navigate to Servers page
      $state.go('app.servers');
    }, 
    function(response) {
      // Track failed logins
      window.analytics.trackFeature("Login.Failure");

      $ionicLoading.hide();
    });
  };
})
....

However, an error is thrown stating that injection cannot be done.

I would appreciate any assistance in identifying the reason for this issue. The message indicates that starter.services is not defined.

Answer №1

The reason for the error lies in your service definition. You have omitted the dependency array [] as the second parameter, causing Angular to interpret it as a getter method for the module starter.services instead of defining the module itself. To resolve this issue, use the following code for starter.services:

angular.module('starter.services', [])
.service('CloudDatabases', ['$http', function ($http) {

    var urlBase = '/api/customers';

    this.getDatabases = function () {
        console.log('CloudDatabases.getDatabases();');
        return 'test getDatabasesResponse';
    };
}])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Understanding the res.render method in JavaScript can be a bit tricky at first

In my spare time, I have been immersing myself in coding lessons and have encountered some puzzling aspects of the code: Firstly, there is a confusion surrounding the action attribute in HTML Secondly, this particular piece of code is causing me some b ...

Using a custom module in node.js to retrieve data from a mysql database

How can I retrieve select query results? I am currently getting empty or null responses. Despite attempting callback logic and using the callback function as suggested in some articles, I have yet to have any success. All of the code for my Custom Module ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...

Leverage JavaScript to update the name of a Google Spreadsheet using the latest data

Here is some code that allows you to rename a document: function renameFile() { var s = SpreadsheetApp.getActiveSpreadsheet(); s.rename("new file name"); } Can you modify this function to rename the file to "new filename 1/18"? Remember, where 18 r ...

Creating a drawImg function on the HTML/JavaScript canvas

Attempting to duplicate a specified section of an image onto a canvas below, but finding that the mirrored section is resizing unexpectedly. For example, if given a map image and trying to replicate a building from it exactly below, why does the mirrored s ...

The search function on my blog is not displaying the blogs that have been filtered

I have encountered an issue with my code as I am unable to get any search results from the search bar. const RecentBlogs = ({recentBlogs}) => { const [query, setQuery] = useState("") const filteredItems = (() => { if(!query) return rec ...

What is the best way to incorporate an AJAX GET request into an HTML element?

Currently, I am attempting to execute a JavaScript code that will convert all <a></a> elements found within another element <b></b> (the specific name in the HTML) into links that trigger an HTTP get request. However, the code I hav ...

Convert image buffer to string using Mongoose getter?

I have developed a basic node backend application modeled after eBay. I am now working on creating a react frontend app to complement it. Within the app, users can list items for sale and include a photo with their listing. The item information is stored ...

Which specific indexOf method is the most appropriate for my use case?

While exploring a codebase, I came across this code snippet that adds the indexOf function: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

``JsViews and AngularJS: A Comparison"

I'm exploring the possibility of creating a single page application and came across jsViews/jsRender which seems very promising as it approaches Beta. As someone new to SPA development, I'm interested in understanding how jsViews stacks up agains ...

The server node proxy is failing to trigger the API call

update 1: After modifying the api path, I am now able to initiate the api call. However, I encountered the following error: (node:13480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): RangeError: Invalid status code: res ...

Unable to retrieve req.body data, despite having body-parser enabled

I've been working on setting up my login functionality, but I'm running into an issue with accessing the req.body object. Initially, the post route wasn't triggering at all (no console.log output in terminal) and the request would eventuall ...

Fetching an image from Firebase Storage for integration into a Vue application

I am encountering an issue while trying to fetch an image from my firebase storage to display it in my Vue application. The upload process from the app to firebase storage runs smoothly, but there is an error during retrieval. My setup involves using the F ...

Cookies are mysteriously invisible in the developer console of Safari/Chrome when using the Set-Cookie Header, yet they miraculously appear in server logs

Storing cookies for my web app using the 'Set-Cookie' header response from my python backend has been a challenge. https://i.stack.imgur.com/XMx35.png An ajax call on the client-end to the function is where I run into issues: https://i.stack.im ...

I'm confused as to why my React application is showing a blank screen even though I successfully imported and used an icon from Material UI. It compiled without any errors

I encountered an issue with my code when I added the "Avatar" line. To fix the problem of material UI not displaying properly, I had to use react icons instead. If possible, I would like recommendations for alternative packages that include the Avatar co ...

Unable to execute functions using an AJAX request

Currently, I am developing a React component that is bound to various actions. During this process, I found the need to call an API from within the component and handle the response accordingly. To achieve this, here is my current approach: In a successfu ...

Using a PHP switch case statement with an HTML multiple select dropdown

I am facing an issue with my HTML multiple select box: <option value="1">First choice</option> <option value="2">Second choice</option> <option value="3">Third choice</option> Using jQuery, ...

Accessing BIM Components: Identifying Global and Express IDs through Selection

As I delve into the task of handpicking specific elements from the intricate web of an IFC model, my approach involves utilizing a SimpleRayCaster to cast a ray onto the object with relative success. The challenge lies in identifying the exact entity inter ...