How to inject a service to the main controller in angularjs? - angularjs

I was able to inject AuthDetails service to other components of my app, but I am having trouble injecting AuthDetails service to my main controller in the app, I have tried following but it does not work. It says: Uncaught ReferenceError: AuthDetails is not defined
MPlayApp.controller('MainCtrl','AuthDetails', [AuthDetails,
function MainCtrl(AuthDetails) {
var subscription = AuthDetails.subscribe(function onNext(d) {
console.log(d);
if(d.success){
this.loggedIn = true;
}
});
}]);
I have added the service to app as follows
var MPlayApp = angular.module('MPlayApp', [
// ...which depends on the MPlayApp module
'player',
'core',
'userMenu',
'home',
'songUpload',
'loginSignUp',
'details',
'angularSoundManager',
'angularFileUpload',
'ngAnimate',
'rx',
'ui.router',
'core.auth'
]);
AuthDetails service is under core.auth module

The syntax is wrong. It should be
MPlayApp.controller('MainCtrl', ['AuthDetails', function MainCtrl(AuthDetails) {
Or better, use ng-annotate, and let it generate this ugly, error-prone syntax for you during the build, from the basic, intuitive syntax:
MPlayApp.controller('MainCtrl', function MainCtrl(AuthDetails) {

Related

components registration and structure errors AngularJS

I've been trying to refactor my old AngularJS app for a better structure, first, i'm breaking down controllers to components , I'm following this syntax, but get error failed to instantiate module, and component not registered. my component looks like:
angular.module('app')
.component('LoginComponent', {})
.controller('LoginController', ['$scope', function ($scope,) { }]);
and in my app.js
var app = angular.module('app', [
'ngMaterial',
'LoginComponent'
]);
in my webpack:
module.exports = {
entry: ['path/login.component.js',
],
};

Browserify AngularJS Module factory method extend another factory method

I'm currently attempting to implement Browserify over an existing application.
I have a requirement where I have a BaseService that contains a bunch of standard functionality e.g. setting standard headers on requests etc.
In my factories I use loadash to extend the BaseService. For this to work I need to have a reference to BaseService in any factory that tries to extend it. I can't figure out how to pass through this dependency now I have started to use browserify.
I've added sample code below.
Module declaration:
'use strict';
var angular = require('angular');
module.exports = angular.module('todoApp.services', [require('../secure').name])
.factory('AuthService', ['$q', 'ConsumerConfig', require('./auth-service')])
.factory('BaseWebService', ['$http', '$q', 'Encryption', 'nativeCrypto', require('./base-web-service')]);
AuthService:
'use strict';
var _ = require('lodash');
module.exports = function($q, ConsumerConfig) {
return _.extend({
config: ConsumerConfig,
authenticate: function (options) {
var deferred = $q.defer();
this.callService({
user: options.user,
url: "/AuthenticateUser",
type: "GET"
}).then(function (response) {
deferred.resolve(response.data.userAuthResponse.responseMessage.Token);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
}, BaseWebService);
};
I would ideally like to use DI to inject the dependency but when I try this I keep getting an unknown provider error. Does anyone know how I can get this working?
For anyone looking - I solved this by creating a new "Core" module and then having my services module require the core module.
This way everything was loaded in the correct order

Angular Services within Modules

Having difficulty injecting a service into another service. I want a service hierarchy, where I can pass/request logic to/from the parent service, for sake of brevity and encapsulation.
So for example, I have a userService, and I want the userService to manage the user's toDoList. So I created a toDoService, and I want controllers to add a toDo for the user by passing the request to the userService, which relays to the toDoService. Here's what I have:
// app.js
angular.module('myApp', [
// other dependencies...
'myApp.myServices'
]);
// services/toDoService.js
angular.module('myApp.myServices', [])
.factory('toDoService', function($http) {
getStuff = function(userId) {
// returns $http call
};
addStuff = function(userId, data) {
// returns $http call
};
});
// services/userService.js
angular.module('myApp.myServices', [])
.factory('userService',
['$http', 'toDoService', function(
$http, toDoService) {
addToDo = function(data) {
toDoService.addStuff(user.uid, data)
.then(function(success) {
// apply bindings
})
.catch(function(error) {
// display error
});
};
getToDos = function(data) {
toDoService.getStuff(user.uid)
.then(function(success) {
// apply bindings
})
.catch(function(error) {
// display error
});
};
}]);
The controller works with the userService, and code from toDoService worked when it was originally in userService. But when I create the toDoService and move that code there and encapsulate it, angular complains about toDoService.
Error: [$injector:unpr] Unknown provider: toDoServiceProvider <- toDoService <- userService
I've checked script references, and all scripts are properly included. e.g. <script src='/[..]/toDoService.js' /> etc...
So I'm wondering is it even possible to inject a service into another service within the same module? Is it an issue with my naming convention?
angular.module('myApp.myServices', [])
This line in userService.js defines the module myApp.services, overwriting the one that has previously been defined in toDoService.js.
Define the module only once (in a separate file). Get a reference to this previously defined module using
angular.module('myApp.myServices')
i.e. without the empty array as second argument.

Angularjs - Uknown Provider

Whenever I do this:
app.controller('hangmanController', ['$scope', 'wordnickAPIService', function ($scope, wordnickAPIService) {
I get this:
[$injector:unpr] Unknown provider: wordnickAPIServiceProvider <- wordnickAPIService
I read through This discussion on the topic, but didn't see an answer that applied. I am sure it is something simple or trivial that I am missing, but, jeez, if Angular isn't giving me fits trying to piece it all together.
Relevant HTML:
<body ng-app="angularHangmanApp" ng-controller="hangmanController">
My controller:
'use strict';
var app = angular.module('angularHangmanApp', []);
app.controller('hangmanController', ['$scope', 'wordnickAPIService', function ($scope, wordnickAPIService) {
[...]variable declarations[...]
var wordListURL = 'http://long_url_that_returns_some_json';
$scope.wordList = wordnickAPIService.get(wordListURL);
}]);
My factory:
'use strict';
var app = angular.module('angularHangmanApp', []);
app.factory('wordnickAPIService', ['$http', function($http) {
return {
get: function(url) {
return $http.get(url);
},
post: function(url) {
return $http.post(url);
},
};
}]);
The problem is that you are creating multiple modules with the same name.
To create a module in angular you use:
var app = angular.module('angularHangmanApp', []);
Then to get That module somewhere else you just type:
var app = angular.module('angularHangmanApp');
No extra []...
Also make sure you declare the service before trying to call it.
In your factory and your controller, you are actually redefining the app module.
Instead of saying
var app = angular.module('angularHangmanApp', []);
say
var app = angular.module('angularHangmanApp');
Use the first style of invocation only once in your application (maybe just app.js). All other references should use the second style invocation, otherwise, you're constantly redefining the angular app and losing all of the controllers, factories, directives declared previously.

Wire up AngularJS controller to express controller

I'm getting started with node/express/Angular by using the MEAN stack at mean.io.
I don't understand how the Angular controller calls the express controller to fetch data.
What I have is public/js/controllers/index.js:
angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'Tabs',
function ($scope, Global, Tabs) {
$scope.global = Global;
Tabs.query(function(tabs) {
$scope.tabs = tabs;
});
}]);
But I'm confused what exactly 'Tabs' is. I know that somehow, magically, eventually this method is called - I think this is the Express controller?
app/controllers/tabs.js:
exports.all = function(req, res) {
Tab.find().sort('artist').select("-content").populate('user').exec(function(err, tabs) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(tabs);
}
});
};
But I don't understand how it gets called. What I want to do is call a different method in app/controllers/tabs.js instead - namely, this:
exports.newest = function(req, res) {
Tab.find().sort('-created').limit(10).select("-content").exec(function(err, tabs) {
...
But I don't understand how to "wire up" the AngularJS controller with the express controller.
i.e. what do I have to do so that I can do something like this in my controller:
angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'Tabs',
function ($scope, Global, Tabs) {
$scope.global = Global;
Tabs.newest(function(tabs) { // this won't work
$scope.tabs = tabs;
});
}]);
In MEAN, The Articles service is an angular service that returns a $resource object you can usually find in the public/js/services folder.
$resource is a wrapper around $http AJAX service that comes with angularjs, it enables you to connect with RESTful endpoints if your REST service is built in a specific manner.
The connection to the the node.js controller happens using the routes.js object found in the config folder that binds routes to specific module methods.
further reading:
http://docs.angularjs.org/api/ngResource.$resource
http://expressjs.com/api.html#app.VERB

Resources