how to call a function on page load in angular service - javascript

Below is how my angular app looks like.
(function () {
"use strict";
angular
.module("app.core", ['ngRoute']);
}());
Service
(function () {
'use strict';
angular
.module('app.service')
.factory('dataService', dataService);
dataService.$inject = ['$http', '$q'];
function dataService($http, $q) {
var service = {
create: create,
read: read,
update: update,
remove: remove
}
return service;
function read() {
return
$http.get("APIURL")
.then(success)
.catch(exception);
function success(response) {
}
function exception(ex) {
}
}
function create() {}
function update() {}
function detete() {}
}
})`
index.html
<body ng-app="app.core">
<div ng-view> </div>
</div>
On page load, home-template.html is inserted into ng-view.
No clue on below
what would be the right way to call only dataService's read() on page
load?

The normal use case is to call the service in the constructor of your controller.
John Papa's style guide has a lot of detailed guidance on this type of architecture and best practices. I'd highly recommend it.
https://github.com/johnpapa/angular-styleguide/tree/master/a1

Related

Simple angular service not working

I am trying to create an angular service but it is not working. I have tried numeros things and looked all over.Please help
//service
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin()
{
this.testFunc = function ()
{
console.log("THIS IS A TEST SERVICE");
}
};
Below: tryoing to call service test func
//controller
angular
.module('RDash')
.controller('ComposeCtrl', ['$scope','$rootScope','$http','googleLogin', ComposeCtrl]);
function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
console.log("ComposeCTRL active");
googleLogin.testFunc(); // this doesnt work, error: "main.min.js:2 Error: [$injector:undef] http://errors.angularjs.org/1.5.8/$injector/undef?p0=googleLogin"
I feel like the issue is with injecting i just dont know where. Please help thanks
Factory needs to return the function refrence and you need to declare variable testFunc (answer to why here):
Update working snippet.
angular.module('RDash', []);
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin() {
var testFunc = function() {
console.log("THIS IS A TEST SERVICE");
}
return {
testFunc : testFunc
}
};
angular
.module('RDash')
.controller('ComposeCtrl', ['$scope', '$rootScope', '$http', 'googleLogin', ComposeCtrl]);
function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
console.log("ComposeCTRL active");
googleLogin.testFunc();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="RDash" ng-controller="ComposeCtrl"></div>
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin() {
var testFunc = function() {
console.log("THIS IS A TEST SERVICE");
}
return {
testFunc: testFunc
}
};

TypeError: api.getAll is not a function, service method is not recognized

I have a very simple service and a controller attempting to get some information from it, but I keep getting .methodName is not a function.
Here is the service, apiService.js :
(function (module) {
function api() {
var sharedService = {};
sharedService = {
getAll: function () {
return 'test';
}
};
return sharedService;
}
module.factory("api", api);
}(angular.module("anbud")));
Then I attempt to use my method getAll in the controller, like this:
(function () {
'use strict';
angular.module('anbud')
.controller('BasicExampleCtrl', ['$scope', 'api', function (api, $scope) {
// on successfull request
function onJson(json) {
$scope.data = json;
}
// error getting json
function onError() {
throw 'error getting json';
}
function initialize() {
api.getAll()
.then(onJson, onError);
}
initialize();
}]);
}());
But I get the error:
TypeError: api.getAll is not a function
at initialize (basic-example.js:67)
Any help is appreciated thank you.
You have interchanged the dependencies sequence inside controller factory function, the sequence must be same as they are included in DI array while injecting in function.
Code
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope, api) { //<- first $scope then api.
try it like this:
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope,api) {

What's wrong with this factory dependencies issue?

I'm working with AngularJS.
I'd like to get a controller using a first factory which using another one.
It could be schematize like that:
MyCtrl -> Factory1 -> Factory2
So I tried to do in 3 different files (loaded in the following order):
Factory2.js
app.factory('Factory2', function () { ... })
Factory1.js
app.factory('Factory1',['Factory2', function (Factory2) { ... })
controller.js
app.controller('MyCtrl',['$scope', 'Factory1', function ($scope, Factory1) { ... })
And in my HTML I have:
<script src="services/factory2.js" type="text/javascript"></script>
<script src="services/factory1.js" type="text/javascript"></script>
<script src="controllers/controller.js" type="text/javascript"></script>
But it doesn't work and I've got this error Unknown provider: Factory2Provider <- Factory2 <- Factory1
What's wrong with my code? Am I missing something?
You can refactor your codes and use modules, in this way you will not need to use $inject
var app = angular.module('app', ['factories', 'mymodule']);
angular.module('factories', [])
.factory('Factory2', function () { })
.factory('Factory1', ['Factory2', function (Factory2) {
return myCustomFunction = function () {
alert('todo');
}
}]);
angular.module('mymodule', [])
.controller('MyCtrl', ['$scope', 'Factory1', function ($scope, Factory1) {
$scope.text = "testing";
}])
http://jsfiddle.net/kL78rdr3/3/
Why don't you use explicit injection with $inject? It is a better approach, because it gives you more control over the dependencies. For example:
userController.js
function userController (model, routeParams, searchService) {
//implementation
}
userController.$inject = ['$scope', '$routeParams', 'searchService'];
app.controller("userController", userController);
searchService.js
var searchService = function (http, log) {
//implementation
}
searchService.$inject = ["$http", "$log"];
app.factory("searchService", searchService);
This post may be useful: Explicit Dependency Injection

Splitting AngularJS Module Services Across Files

I have two AngularJS services:
service1.js
'use strict';
angular.module('myModule', [])
.factory('myService1', function() {
return {
myFunction: function(options) {
if (options) {
// do stuff
}
}
};
});
service2.js
'use strict';
angular.module('myModule', [])
.factory('myService2', function() {
return {
myFunction: function(options) {
if (options) {
// do stuff
}
}
};
});
I learned the hard way from the official docs that this approach will basically remove myService1 because the module gets overwritten. My question is, do I have any options here? I would really like to be able to have my services defined in separate files. Yet, I only want one module.
Thank you for any insights.
You have to define the module just once:
angular.module('myModule', []);
And then use it as many times as you need it without setting the dependencies:
angular.module('myModule');
So either you define the module in a separate file, or if you define it in the first service, the second should look like this:
angular.module('myModule')
.factory('myService2', function() { ... });

Argument 'fn' is not a function got string

I have a part in my angular application on which I've binded a controller,
since then I got the Argument 'fn' is not a function Error, can anyone look at my code and explain why I got that Error?
I would be very gratefull :)
html-markup:
<section class="col-lg-12" data-ng-controller="MessageController">
<fieldset>
<legend>{{ 'MESSAGES' | translate }}</legend>
</fieldset>
<div class="margin-left-15">
<ul class="list-style-button">
<li data-ng-repeat="message in MSG">{{ message }}</li>
</ul>
</div>
</section>
controller:
(function() {
'use strict';
var controllers = angular.module('portal.controllers');
controllers.controller('MessageController', ['$scope', 'MessageService', '$rootScope', function MessageController($scope, MessageService, $rootScope) {
$rootScope.MSG = MessageService.getMessages();
$rootScope.$watch('MSG', function(newValue) {
$scope.MSG = newValue;
});
}]);
}());
Service:
(function() {
'use strict';
var messageServices = angular.module('portal.services');
messageServices.factory('MessageService', ['MessageData', 'localStorageService', 'UserService'], function(MessageData, localStorageService, UserService) {
return new MessageService(MessageData, localStorageService, UserService);
});
function MessageService(MessageData, localStorageService, UserService) {
this.messageData = MessageData;
this.localStorageService = localStorageService;
this.userService = UserService;
}
MessageService.prototype.getMessages = function() {
var locale = this.userService.getUserinfoLocale();
var messages = this.localStorageService.get(Constants.key_messages + locale);
if (messages !== null && messages !== undefined) {
return JSON.parse(messages);
} else {
return this.messageData.query({
locale: locale
}, $.proxy(function(data, locale) {
this.save(Constants.key_messages + locale, JSON.stringify(data));
}, this));
}
};
MessageService.prototype.save = function(key, value) {
this.localStorageService.add(key, value);
};
}());
data:
(function() {
'use strict';
var data = angular.module('portal.data');
data.factory('MessageData', function($resource) {
return $resource(Constants.url_messages, {}, {
query: {
method: 'GET',
params: {
locale: 'locale'
},
isArray: true
}
});
});
}());
order of js files in html head:
<script src="js/lib/jquery-1.10.js"></script>
<script src="js/lib/angular.js"></script>
<script src="js/lib/angular-resource.js"></script>
<script src="js/lib/angular-translate.js"></script>
<script src="js/lib/angular-localstorage.js"></script>
<script src="js/lib/jquery-cookies.js"></script>
<script src="js/lib/bootstrap.js"></script>
<script src="js/portal.js"></script>
The problem was in using the 'wrong' syntax to create the service
instead of using:
messageServices.factory('MessageService',
['MessageData','localStorageService', 'UserService'],
function(MessageData, localStorageService, UserService){
return new MessageService(MessageData, localStorageService, UserService);
}
);
I had to use:
messageServices.factory('MessageService',
['MessageData','localStorageService', 'UserService',
function(MessageData, localStorageService, UserService){
return new MessageService(MessageData, localStorageService, UserService);
}
]);
I closed the array with parameters to soon, and since I'm still learning I didn't see it directly, anyhow I hope I can help others who stumble upon this.
Today I got the same kind of error doing that silly mistake:
(function(){
angular
.module('mymodule')
.factory('myFactory', 'myFactory'); // <-- silly mistake
myFactory.$inject = ['myDeps'];
function myFactory(myDeps){
...
}
}());
instead of that:
(function(){
angular
.module('mymodule')
.factory('myFactory', myFactory); // <-- right way to write it
myFactory.$inject = ['myDeps'];
function myFactory(myDeps){
...
}
}());
In fact the string "myFactory" was brought into the injector who was waiting for a function and not a string.
That explained the [ng:areq] error.
The above answers helped me considerably in correcting the same issue I had in my application that arose from a different cause.
At built time, my client app is being concatenated and minified, so I'm writing my Angular specifically to avoid related issues. I define my config as follows
config.$inject = [];
function config() {
// config stuff
}
(I define a function, $inject it as a module and declare what it is).
And then I tried to register the config just as I registered other modules in my app (controllers, directives, etc..).
angular.module("app").config('config', config); // this is bad!
// for example, this is right
angular.module("app").factory('mainService', mainService);
This is wrong, and gave me the aforementioned error. So I changed to
angular.module("app").config(config);
And it worked.
I guess the angular devs intended config to have a singular instance and by so having Angular not accept a name when config is registered.
I had the same issue and In my case the problem was with angular-cookies.js file. It was in folder with other angularjs scripts and when I have used gulp to minify my js files the error occured.
Simple solution was just to place the angular-cookies.js file to another folder, outside the selected folder to minify js files.
My case
let app: any = angular.module("ngCartosServiceWorker"),
requires: any[] = [
"$log",
"$q",
"$rootScope",
"$window",
"ngCartosServiceWorker.registration",
PushNotification
];
app.service("ngCartosServiceWorker.PushNotification");
I forgot to add requires Array as parameters to service like this
app.service("ngCartosServiceWorker.PushNotification", requires);

Categories