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

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.

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) {

Related

Error when trying to load require module

I've been trying to understand how to set up Stripe for my app but am having problems with the implementation of the module. Normally when using a module i would require it in the top of the file to be able to use it but when i do it in the paymentCtrl file it doesn't work and i get the two errors below: where am i supposed to declare it for me to be able to use it? Well as you see i'm quite new to this and would like to understand how to structure this so that the payments work.
errors:
Unexpected token.
and
Failed to instantiate module paymentController due to:
Error: [$injector:nomod] Module 'paymentController' 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.
paymentCtrl:
angular.module('paymentController', [])
var stripe = require('stripe')('sk_test_....');
.controller('paymentCtrl', function($scope) {
});
app.js:
angular.module('userApp', ['appRoutes', 'userControllers', 'userServices', 'ngAnimate', 'mainController', 'authServices', 'managementController', 'paymentController'])
.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptors');
});
try to move line:
var stripe = require('stripe')('sk_test_....');
above line:
angular.module('paymentController', [])

Error: $injector:modulerr Module Error in angular

var myapp = angular.module('myapp', []);
myapp.config(function($interpolateProvider) {
$interpolateProvider
.startSymbol('{[')
.endSymbol(']}');
});
myapp.controller('CanvasControls', function($scope) {
function1($scope);
function2($scope);
});
This code integrate with rails and working in development fine but in production mode it gives below errors.
Failed to instantiate module myapp due to:
Uncaught Error: $injector:modulerr
/$injector/modulerr?p0=myapp
working in development fine but in production mode it gives below
errors
Guess in production you are compressing the code.And I presume you have to add $scope like this
Hope this will help
// Changed here Added String '$scope'
myapp.controller('CanvasControls',['$scope', function($scope) {
function1($scope);
function2($scope);
}]);
EDIT
If you have not modified the .config part please try by making following change.
customInterpolationApp.config(['$interpolateProvider', function($interpolateProvider){
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
}]);
More about such error
Syntax error added extra ] in controller
myapp.controller('CanvasControls', function($scope) {
function1($scope);
function2($scope);
}]);// remove ']' from here
or use mini-fist way
myapp.controller('CanvasControls', ['$scope',function($scope) {
function1($scope);
function2($scope);
}]);
and you may mismatch module name myapp in controller and in html ng-app="myapp"

Angularjs - Dynamic configuration based on Environment

I have a sample angular APP - app.js
angular
.module('myUiApp', [
'restangular',
'ngRoute',
'ngCookies',
'ui.bootstrap',
'ui.sortable',
'smart-table',
'config'
])
.config(function($routeProvider, $httpProvider, $sceProvider, $logProvider, RestangularProvider, config) {
RestangularProvider.setBaseUrl(config.apiBaseUrl);
RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});
//routing here
.....
});
my Config.js looks like -
angular.module('config', []).service('config', function($location, ENV) {
return ENV.dev;
});
my constants.js looks like -
'use strict';
angular.module('config', []).constant('ENV', (function() {
return {
dev: {
appBaseUrl:'http://localhost:9000/',
apiBaseUrl:'http://localhost:8082/api/'
}
}
})());
I am getting the error saying, Failed to instantiate module myUiApp due to:
[$injector:unpr] Unknown provider: config.
My assumption is injecting config module will invoke the service, which in turn return the json object. any thoughts or suggesstions to do this dynamic config better?
You can only inject providers into an angular .config() block. You're attempting to inject a service, and that is likely the cause of your error.
Also, you have angular.module('config', []) in two different places. This should only be used once to instantiate the module. Use angular.module('config') (without the second argument) subsequently to reference that module.
I would avoid calling the module config, in favor of something that isn't a method used by angular module.config() -- maybe myConfigModule
Secondly, make sure your script includes the constants.js file and the Config.js file before it includes the app.js file
Lastly double check that this situtation is not affecting you:
defining the module twice with angular.module('config', []) ( emphasis on the [ ] ..) When you define the module with the square brackets, you are saying "New Module". In the second file that you include, change it to angular.module('config') -- or, combine the files into this:
angular.module('myConfigModule', [])
.constant('ENV', (function() {
return {
dev: {
appBaseUrl:'http://localhost:9000/',
apiBaseUrl:'http://localhost:8082/api/'
}
}
}).service('config', function($location, ENV) {
return ENV.dev;
});
UPDATE: And typically I see this syntax for controllers, services, anything that is injecting anything else
.service('config', ['$location', 'ENV', function($location, ENV) {
return ENV.dev;
}]); // see beginning and end of square bracket
// also add new injected modules to both the array (surrounded by quotes) and the function

Why is my directives module not being included in my Angular app module?

Just learning Angular and I'm encountering a few issues with module resolution. In js/directives/directives.js I have the following directive scoped to a directives module:
angular.module("directives").directive("selectList", function() {
return {
restrict: 'E',
link: function() {
// do stuff
}
}
});
On my webpage:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script>
angular.module("editUserApp", ["directives"])
.controller("editUserController", ['$http', '$scope', function($http, $scope) {
// do stuff here
}]
);
</script>
The error I'm getting is as follows:
Error: [$injector:modulerr] Failed to instantiate module editUserApp due to:
[$injector:modulerr] Failed to instantiate module directives due to:
[$injector:nomod] Module 'directives' 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.
Now, obviously, editUserApp cannot know where directives is, all by itself, so how do I tell it to fetch the directives.js file? Do I have to include it in a script tag (which doesn't seem very scalable)?
I need some way to import directives to my angular app. How can I do this?
You need to include your js/directives/directives.js file into your html and remove the directives dependency on your App module.
your code should be :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script>
angular.module("editUserApp", [])
.controller("editUserController", ['$http','directives', '$scope', function($http, $scope,directives) {
// do stuff here
}]
);
</script>
You need
angular.module("directives" ,[])
in your first block
angular.module("directives")
tries to find an existing module called directives
If you are looking for a way to import these files on a as needed basis, you might want to look at http://requirejs.org/ or http://browserify.org/ or similar tools.

Including Angular configuration Module

I have trouble building an Angular module that stores all the configuration data and then including it in my main Angular module.
The idea is for the system to be able to change the configuration data. So the main Module code and controller codes are the same but the config module is different.
I have tried many different way to get this to work but they all give me a series of errors.
My config modules looks like this
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
});
My main (condensed) module looks like this. Note I'm using it with a blade template for the brackets.
(function( ){
var app = angular.module('favoriteeats', ['favoriteeats.config','ngResource'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
})();
My controller looks like this.
(function( ){
var app = angular.module('favoriteeats');
app.controller('EntrustRolePermissions', function($scope, $controller) {
angular.extend(this, $controller('BaseController', {$scope: $scope}));
var vm = this;
vm.roles = [ ];
vm.user_roles = [ ];
vm.updateRoles = function(){
ret = vm.restApi('role','GET');
console.log(ret);
}
vm.updateRoles( );
}) //end contoller
})();
When I include the config module script in the head I get this error.
"Error: [$injector:modulerr] Failed to instantiate module favoriteeats due to:
[$injector:modulerr] Failed to instantiate module favoriteeats.config due to:
[$injector:nomod] Module 'favoriteeats.config' 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."
When I include the config module script in the footer after lazying loading the JS I get the same error.
If I add the config module script to a separate JS file and add this before or after the main module js file I get the same error.
The only way it seem to work is if I included in the same `(function( ){' container as the main module. IE
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
var app = angular.module('favoriteeats', ['favoriteeats.config','ngResource'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
})();
Why is this? How can I extract it and include my config script from another location!?!? I cannot find the answer to determine what is wrong.
You should declare a module by indicating its dependencies (in this case an empty array) and then you have to execute the function:
(function( ){
angular.module('favoriteeats.config', [])
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
})();
You're referencing the 'favoriteeats.config' module instead of defining it. If you add the empty list of dependencies, it should work.
angular.module('favoriteeats.config', [])
You have a faulty IIFE.
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
}); // This does not close the IIFE.
Change it to:
(function( ){
angular.module('favoriteeats.config')
.constant('GLOBAL_CONFIG', {
'base_uri': '".url( )."'
});
}()); // or })();
edit; I didn't even pay attention to the fact that you are not defining your module, but rather referencing it. Like #joao and #mithon suggested - add some brackets:
angular.module('favoriteeats.config', [])

Categories

Resources