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.
Related
I am trying to configure my Module with a Provider that should allow a custom configuration. This is my Provider:
var module = angular.module('myModule', []);
module.provider('MyModule', function () {
this.setBaseUrl = function (f) {
this.BaseUrl = f;
};
this.setOnForbidden = function (f) {
this.onForbidden = f;
};
this.setOnTokenExpired = function (f) {
this.onTokenExpired = f;
};
this.setOnUnauthenticated = function (f) {
this.onUnauthenticated = f;
};
this.$get = function () {
return this;
};
})
And this is my App that uses the Provider:
angular.module('myApp', ['myModule'])
.config(function (MyModuleProvider) {
MyModuleProvider.setBaseUrl("http://localhost:8080/");
MyModuleProvider.setOnForbidden(
function () {
console.log("Forbidden - User Function");
}
);
MyModuleProvider.setOnTokenExpired(
function () {
console.log("Token Expired - User Function");
}
);
MyModuleProvider.setOnUnauthenticated(
function () {
console.log("User Unauthenticated, wrong username or password - User Function");
}
);
})
The three functions setOnForbidden, setOnTokenExpired and setOnUnauthenticated are working fine alone, but when I add the MyModuleProvider.setBaseUrl("http://localhost:8080/"); it returns the following error:
Failed to instantiate module myApp due to:
TypeError: MyModuleProvider.setBaseUrl is not a function
Why? Is there something wrong in the Provider code?
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);
}
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?
I have a factory which get data from server. In the factory method I have used $cacheFactory to cache getting data. My code is as follows..
var buyersService = function ($http, $q,$cacheFactory) {
var serviceBase = '/api/OMData/';
var BuyersFactory = {};
buyersService.cache = $cacheFactory('cacheId');
BuyersFactory.GetBuyers = function () {
var dataList = buyersService.cache.get('BuyerData');
if (dataList != null && dataList.length > 0) {
return dataList;
}
else {
return $http.get(serviceBase + 'GetBuyers').then(
function (results) {
buyersService.cache.put("BuyerData", results.data);
return results.data;
});
}
}
app.factory('OMDataService', ['$http', '$q', '$cacheFactory', buyersService]);
});
Now I have called GetBuyers method from controller. My method is like below..
var BuyerController = function ($scope, BuyersService) {
$scope.Buyers = [];
init();
function init() {
getBuyers();
}
function getBuyers() {
BuyersService.GetBuyers()
.then(function (data) {
$scope.Buyers = data;
}, function (error) {
alert(error.message);
});
}
};
app.register.controller('BuyersController', ['$scope', 'OMDataService', BuyerController]);
When I have executed my controller method second time I have got an error message in promise part.
Object doesn't support property or method 'then'
The issue here is that your function returns two different things: either a promise or plain data. To remedy this, use another promise to control the flow and return that one as the result of the function.
Update your code to
var buyersService = function ($http, $q,$cacheFactory) {
var serviceBase = '/api/OMData/';
var BuyersFactory = {};
buyersService.cache = $cacheFactory('cacheId');
BuyersFactory.GetBuyers = function () {
var buyersDataIsAvailable = $q.defer();
var dataList = buyersService.cache.get('BuyerData');
if (dataList != null && dataList.length > 0) {
buyersDataIsAvailable.resolve(dataList);
}
else {
$http.get(serviceBase + 'GetBuyers').then(
function (results) {
buyersService.cache.put("BuyerData", results.data);
buyersDataIsAvailable.resolve(results.data);
});
}
return buyersDataIsAvailable.promise;
}
app.factory('OMDataService', ['$http', '$q', '$cacheFactory', buyersService]);
});
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!