How to use constant in angularjs - angularjs

How i can use constant in angular, i want to attach a constant value via factory. Please check the following code
/* Factory which attach the constant in app module */
'use strict';
define(['app'], function (app) {
var traslationParams = ['$resource'];
var translationFactory = function (resource) {
return {
attachTranslator: function (language) {
var languageFilePath = applicationUrl.clientUrl + '/translation/translation_' + language + '.json';
resource(languageFilePath).get(function (data) {
app.constant('languagePack', data); // registering constant
});
}
}
}
translationFactory.$inject = traslationParams;
app.factory('translationFactory', translationFactory);
});
// I am executing the factory api to register the constant using following code
app.run([ 'translationFactory', function ( translationFactory) {
translationFactory.attachTranslator('da');}]);
// The usage of constant in controller
var companyController = function (languagePack) {
scope.languagePack = languagePack;
console.log(languagePack);
}
but i am getting an error in my controller
Error: [$injector:unpr] Unknown provider: languagePackProvider <- languagePack <- companyController

Add languagepack as a translationFactory attribute and save the translation output to this attribute. Further reference this attribute through service in the controller.
'use strict';
define(['app'], function (app) {
var traslationParams = ['$resource'];
var translationFactory = function (resource) {
return {
languagePack: {},
attachTranslator: function (language) {
var trans = this;
var languageFilePath = applicationUrl.clientUrl + '/translation/translation_' + language + '.json';
resource(languageFilePath).get(function (data) {
//app.constant('languagePack', data); // registering constant
trans.languagePack = data
});
}
}
}
translationFactory.$inject = traslationParams;
app.factory('translationFactory', translationFactory);
});
app.run([ 'translationFactory', function ( translationFactory) {
translationFactory.attachTranslator('da');}]);
var companyController = function (translationFactory) {
scope.languagePack = translationFactory.languagePack;
console.log(scope.languagePack);
}

Related

Error: [$injector:unpr] Unknown provider: musicServiceProvider <- musicService <- MusicController

I have trying to add a service to fetch data from API .
But its gives an error
Error: [$injector:unpr] Unknown provider: musicServiceProvider <-
musicService <- MusicController"
Controller
(function (app) {
var MusicListController = function ($scope, musicService) {
$scope.message = " Jagadish K M";
musicService.getAll().then(function (response) {
$scope.musics = response.data;
console.log($scope.musics);
});
};
app.controller("MusicController", MusicListController);
}(angular.module("theMusic")));
Service
(function (app) {
var musicService = function ($http, musicApiUrl) {
var getAll = function () {
return $http.get(musicApiUrl);
};
var get = function () {
return $http.get(musicApiUrl);
}
var getById = function (id) {
return $http.get(musicApiUrl + id);
};
var update = function (music) {
return $http.put(musicApiUrl + music.id, music);
};
var create = function (music) {
return $http.post(musicApiUrl, music);
};
var destroy = function (id) {
return $http.delete(musicApiUrl + id);
};
return {
getAll: getAll,
getById: getById,
update: update,
create: create,
};
};
app.factory("musicService", musicService);
}(angular.module("theMusic")));
I am newbie in angular. Thanks in advance
You didn't inject your service.
angular.module("theMusic", ["musicService"])
You should take a look to AngularJS Dependency Injection documentation.

Jasmine + AngularJS: How do i test a firebaseio call

I have an angular service class : -
'use strict';
angular.module('triggerTips')
.service('userData', function ($rootScope, $http, $log, $firebase) {
this._log = {
service : 'userData'
};
// Synchronized objects storing the user data
var config;
var userState;
// Loads the user data from firebase
this.init = function(readyCallback) {
var log = angular.extend({}, this._log);
log.funct = 'init';
var fireRef = new Firebase('https://luminous-inferno-1740.firebaseio.com/' + $rootScope.clientName);
config = $firebase(fireRef.child('config')).$asObject();
userState = $firebase(fireRef.child('userState').child($rootScope.userName)).$asObject();
Promise.all([config.$loaded(), userState.$loaded()]).
then(
function() {
if(config == null || Object.keys(config).length < 4) {
log.message = 'Invalid config';
$log.error(log);
return;
}
if(!userState.userProperties) {
userState.userProperties = {};
}
if(!userState.contentProperties) {
userState.contentProperties = {};
}
log.message = 'User Properties: ' + JSON.stringify(userState.userProperties);
$log.debug(log);
log.message = 'Content Properties: ' + JSON.stringify(userState.contentProperties);
$log.debug(log);
log.message = 'Loaded user data from firebase';
$log.debug(log);
readyCallback();
},
function() {
log.message = 'Unable to load user data from firebase';
$log.error(log);
}
);
};
// Returns the initial tip configuration
this.getConfig = function() {
return config;
};
});
I am trying to unit test this service using jasmine:-
my unit test is :-
describe('Service: userData', function () {
// load the service's module
beforeEach(function() {
module('triggerTips');
});
// instantiate service
var userData;
var rootScope;
beforeEach(inject(function (_userData_, $rootScope) {
rootScope = $rootScope;
userData = _userData_;
}));
it('should load correctly', function () {
expect(!!userData).toBe(true);
});
describe('after being initialized', function () {
beforeEach(function(done) {
// Unable to get this working because the callback is never called
userData.init(function() {
done();
});
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
});
it('should have a valid config', function (done) {
setTimeout(function() {
expect(Object.keys(userData.getConfig()).length > 3);
done();
}, 1500);
});
});
});
I am new with this I am receiving an error :
Error: Firebase.child failed: First argument was an invalid path: "undefiend".
Can somebody help me providing working example of my code with some explanation?

How can i return my firebase-data to $scope using resolve

There is a service I use to get data from firebase:
'use strict';
angular.module('flbi.services.trainings', [])
.factory('trainingsService', ['FBURL',
function(FBURL) {
return {
getList: function() {
var queryLimit = 10;
var firebase = new Firebase(FBURL);
firebase.child('trainings').limit(queryLimit).on('value', function(trainings) {
var allTrainings = trainings.val();
$.each(allTrainings, function(training) {
firebase.child('users/' + allTrainings[training].userid).on('value', function(user) {
allTrainings[training].user = user.val();
allTrainings[training].user.gravatar = MD5(allTrainings[training].user.email);
});
});
});
}
};
}]);
The function getList() is called from:
$routeProvider
.when('/', {
controller: 'trainingsCtrl',
templateUrl: 'views/default.html',
resolve: {
"trainings": function(trainingsService) {
return trainingsService.getList();
}
}
})
And the controller:
'use strict';
angular.module('flbi.controllers.trainings', ['flbi.services.trainings'])
.controller('trainingsCtrl', ['$scope', 'trainings',
function($scope, trainings) {
console.log(trainings); <-- just empty ....
$scope.trainings = trainings;
}]);
How can I return the data of allTrainings to my controller? I always get an empty Object. But if I check console.log(allTrainings) inner the on()-method of the service, it is full of data...
You resolve method must return a promise in order for this to work as expected. So your getList method should return a promise.
Also, prefer snapshot.forEach() to using .val() as this is highly optimized (it iterates the pointers rather than parsing and collecting all the data into an object and it also sorts the records to match the data, since JavaScript objects are inherently unordered).
angular.module('flbi.services.trainings', [])
.factory('trainingsService', ['FBURL', '$q',
function(FBURL, $q) {
return {
getList: function() {
var def = $q.defer();
var queryLimit = 10;
var firebase = new Firebase(FBURL);
firebase.child('trainings').limit(queryLimit).on('value', function(trainings) {
var promises = [];
var allTrainings = {};
trainings.forEach(function(ss) {
var key = ss.name();
var d = $q.defer();
promises.push(d.promise);
// put any other data you need in the trainings keys here
// allTrainings[key].widget = ss.child('widget').val();
firebase.child('users/' + allTrainings[key].userid).on('value', function(user) {
allTrainings[key].user = user.val();
var email = user.child('email').val();
allTrainings[key].user.gravatar = MD5(email);
d.resolve();
}, d.reject);
$q.when(promises).then(function() {
def.resolve(allTrainings);
}, def.reject);
});
}, def.reject);
return def.promise;
}
};
}
]);

AngularJS - Injecting factory from another module into a provider

I have a factory from a separate module that I would like to inject into a provider for my module, but I keep getting unknown provider errors. What am I doing wrong?
What I would like to inject:
var angularSocketIO = angular.module('socketioModule', []);
angularSocketIO.factory('socketio', [
'$rootScope',
'addr',
function($rootScope, addr) {
var socket = io.connect(addr,{
'sync disconnect on unload': true
});
...
return socket;
}
]);
Where I am trying to inject it:
angular.module('myApp.services', ['socketioModule'])
.provider('greeter', ['socketio', function(socket) {
var salutation = 'Hello';
this.setSalutation = function(s) {
salutation = s;
}
function Greeter(a) {
this.salutation = salutation;
socket._emit('hello')
this.greet = function() {
return salutation + ' ' + a;
}
}
this.$get = function(version) {
return new Greeter(version);
};
}]);
That results in
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:modulerr] Failed to instantiate module myApp.services due to:
[$injector:unpr] Unknown provider: socketio
I think is because all the providers are instantiated before the factories and so a provider has to depend only on other providers.
As a way around that, I am using the injector method of angular.module to create the module.
A plunker that should do what you were trying to accomplish: http://plnkr.co/edit/g1M7BIKJkjSx55gAnuD2
Notice that I changed also the factory method. The factory method is now returning an object
with a connect method.
var angularSocketIO = angular.module('socketioModule', ['ng']);
angularSocketIO.factory('socketio', [
'$rootScope',
function($rootScope) {
return {
connect: function(addr) {
var socket = io.connect(addr, {
'sync disconnect on unload': true
});
return socket;
}
};
}]);
angular.module('myApp.services', ['socketioModule'])
.provider('greeter', [
function() {
var injector = angular.injector(['socketioModule']);
var socketio = injector.get('socketio');
var salutation = 'Hello';
this.setSalutation = function(s) {
salutation = s;
}
function Greeter(a) {
this.salutation = salutation;
socket._emit('hello');
this.greet = function() {
return salutation + ' ' + a;
};
}
this.$get = function(version) {
return new Greeter(version);
};
}
]);
var myApp = angular.module('myApp', ["myApp.services"]);
I think you can add dependencies via $get method in provider:
angular.module('myApp.services', ['socketioModule'])
.provider('greeter', [
function() {
...
this.$get = ['socketio', function(socket, version) {
function Greeter(a) {
this.salutation = salutation;
socket._emit('hello')
this.greet = function() {
return salutation + ' ' + a;
}
}
return new Greeter(version);
}];
}
]);

Failed to instantiate module ng due to: Error: [$injector:unpr] http://errors.angularjs.org/undefined/$injector/unpr?p0=%24logProvider

I create this to decorate the $log:
window.fofr = window.fofr || {};
window.fofr.library = window.fofr.library || {};
window.fofr.library.logging = window.fofr.library.logging || {};
window.fofr.library.logging.errorLogViewerService = function () {
var configure = function (angularJsModule) {
angularJsModule.config(function ($provide) {
$provide.decorator('$log', function ($delegate, $sniffer) {
var _error = $delegate.error; // Saving original function
var _log = $delegate.log;
$delegate.logs = [];
$delegate.error = function (msg) {
_error(msg);
};
$delegate.log = function (msg) {
_log(msg);
$delegate.logs.push(msg);
};
return $delegate;
});
});
};
return {
configure: configure
};
} ();
I create a unit test with qunit:
module('Library - Logging - ErrorLogViewer', {
setup: function () {
this.app = angular.module('app', []);
}
});
test('Log - check the logs is filled with log', function () {
window.fofr.library.logging.errorLogViewerService.configure(this.app);
var injector = angular.injector(['app', 'ng']);
injector.invoke(function ($log) {
$log.log('test');
equal($log.hasOwnProperty('logs'), true, 'The property logs must exists');
equal($log.logs.length, 1, 'The logs must contain one log');
});
});
But it crash in the config saying that it doesn't know the logProvider???
ok, I found, the $log is defined in ng module, angular search in module defined by the order set in the code : angular.injector(['app', 'ng']);
so I set this angular.injector(['ng', 'app']); and now it works!

Resources