Angularjs - unable to inject $ionicHistory into service - angularjs

Trying to inject $ionicHistory into service itself.
Can I write like this?
.service('$ionicUtilityService', ['CONSTANT', '$log', '$ionicHistory', function(CONSTANT, $log, $ionicHistory) {
var apis = {};
apis.clearNavigationHistory = function() {
$ionicHistory.clearHistory();
};
return apis;
}]);
I am getting error
Error: $ionicHistory is undefined
apis.clearNavigationHistory#http://localhost:8100/js/services.min.js:1:6223
#http://localhost:8100/components/customer/home/home-controller.min.js:1:206
jf/this.$gethttp://localhost:8100/lib/ionic/js/ionic.bundle.min.js:170:424
D.create/O.emit#http://localhost:8100/lib/ionic/js/ionic.bundle.min.js:446:19204
D.create/O.transition#http://localhost:8100/lib/ionic/js/ionic.bundle.min.js:446:18728

Have you tried injecting it elsewhere?
I tried this:
.factory('MyService', function(TestService, $ionicHistory)
{
var service {
myMethod: function(){$ionicHistory.goBack()}
}
return service
}
And got no errors.

Related

Using AngularJS Service in Controller

Service:
app.service('myService', ['$scope', '$timeout', function($scope, $timeout){
return {
fn: function(messageTitle, messageContent) {
$timeout(function() {
$scope.fadeMessageSuccess = true;
}, 3000);
}
}
}]);
Controller:
app.controller("AccountCtrl", ["$scope", "Auth", "$timeout", "myService",
function($scope, Auth, $timeout, myService) {
myService.fn();
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
// Create a new user
Auth.$createUserWithEmailAndPassword($scope.accountEmailAddress, $scope.accountPassword)
.then(function(firebaseUser) {
$scope.message = "User created with uid: " + firebaseUser.uid;
console.log($scope.message);
}).catch(function(error) {
$scope.error = error;
console.log($scope.error);
});
};
}
]);
I'm trying to create a service so that I can use a function in multiple controllers but I'm have trouble getting this first one working. This is the error message I'm getting in console:
angular.js:13550Error: [$injector:unpr]
Just an observation: doesn't look like you're passing anything to the function when you're calling it. And not sure if you're wanting to add any more functionality to the service, but I think you can return the function directly and just call "myService(title, content);". But I don't think those issues would cause what you're encountering.
It looks like you were trying to return an object (a la the .factory() function) when you were trying to use .service(). Here is a dead simple explanation for .factory, .service, and .provider.
As pointed out by user2341963, injecting $scope into a service doesn't make much sense.
Also, are you sure all of your dependencies are defined and available to Angular?
Here is an example Plunkr of using a service in a controller.

how to get variable from different AngularJS file?

How is it possible to get $scope variable from different file (with different module)? For example, I have two files - index.js and login.js, I want to get username from login.js in index.js. I tried to use services but couldn't achieve that goal. The controller doesn't see service in another angular file.
Codes partially are given below:
bookApp.controller('bookListCtrl', ['sharedProperties', function($scope, $http, sharedProperties) {
'use strict';
$scope.name = "Alice";
console.log("in book controller");
console.log("getting login name: "+sharedProperties.getProperty());
and
var authentication = angular.module('authentication', []);
authentication.service('sharedProperties', function () {
var property = 'First';
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
I got this exception -
angular.min.js:63 Error: Unknown provider: authentication.sharedPropertiesProvider <- authentication.sharedProperties
at Error (native)
at
There are 2 problems in the given implementation. The first problem is that the module 'authentication' needs to be a dependency for the consuming modules. The second problem is in the declaration of bookListCtrl. It needs to be defined as follows.
bookApp.controller('bookListCtrl', ['$scope','$http','sharedProperties', function($scope, $http, sharedProperties){
}]);
Can you give an example how you've used services?
Normally if you define controllers like:
app.controller('LoginController', ['UserService', function($scope) {
$scope.someMethod = function(){
// push information to service
UserService.username = $scope.username;
}
}]);
app.controller('IndexController', ['UserService', function($scope) {
// pull information from service
$scope.username = UserService.username;
}]);
It should work. I must suggest you thou to use Controller as instead of $scope. More info here: https://docs.angularjs.org/api/ng/directive/ngController

Injecting $http in angular - Cannot read property 'get' of undefined

I am trying to make an http call function in angular. The problem is that when I try running this on the Chrome console, it says "cannot read get of undefined." Obviously this is referring to the http get call, but it really looks to me like the http dependency was injected, so I am not sure what I am missing.
angular.module('app').controller("MainController", function($http, $scope ){
var vm = this;
vm.title = 'title';
vm.input = '';
$scope.submit = function (input, $scope, $http) {
$http.get("insert-url-here")
.success(console.log(input));
}
}
maybe you have some syntax error.
last time i worked with angular and the $http service i did something like this:
angular.module('app').controller('MainController', ['$scope', '$http', function($http, $scope ){
var vm = this;
vm.title = 'title';
vm.input = '';
$scope.submit = function (input) {
$http.get("insert-url-here")
.success(function(responseData) {
console.log(input));
});
}
//console.log(vm.input);
}]
You don't want to inject $scope and $http in your function. Injecting into you controller is sufficient. Should look like this:
$scope.submit = function (input) {
$http.get("insert-url-here")
.success(console.log(input));
//console.log(vm.input);
})]

Using $http with $exceptionHandler

I want to post errors that happen inside an angular application.
I followed the approach given in this related question, as suggested in the answer, I injected the $injector and then got the $http service from there.
But the line
Uncaught Error: Circular dependency: $http <- $exceptionHandler <- $rootScope
keeps comming.
here is the fiddle with the problem
with the relevant code:
var mod = angular.module('test', []);
mod.config(function ($provide) {
$provide.decorator("$exceptionHandler", ['$delegate', '$injector', function ($delegate, $injector) {
var $http = $injector.get("$http");
}]);
});
mod.controller('testCtrl', function ($scope) {
});
If you comment the line
var $http = $injector.get("$http");
The circular dependency error is gone.
I think I'm missing something in my understanding. What am I doing wrong? After all, that seems to have worked for others.
Any suggestion on how to achieve my initial goal of 'posting errors to a service' is also welcomed.
Thanks everyone
wrap your injector code within function
var mod = angular.module('test', []);
mod.config(function ($provide) {
$provide.decorator("$exceptionHandler", ['$delegate', '$injector',function ($delegate, $injector) {
return function (exception, cause) {
var $http = $injector.get("$http");
}
}]);
});
mod.controller('testCtrl', function ($scope) {
});
You can do like this.
This will break your circular dependency error and you can achieve your goal too.
If I am not wrong then you just wanna call web service in exception Handler.
var httpCallOnAngularError = angular.module('exceptionTestApp', []);
/*httpCallOnAngularError.factory('$exceptionHandler', function () {
return function (exception, cause) {
alert(exception.message);
};
});*/
httpCallOnAngularError.config(function ($provide) {
$provide.decorator("$exceptionHandler", function ($delegate, $injector) {
return function (exception, cause) {
var $rootScope = $injector.get('$rootScope');
$delegate(exception, cause);
$rootScope.logAngularError();
alert(exception.message);
};
});
});
httpCallOnAngularError.run(function ($http, $rootScope) {
$rootScope.logAngularError = function () {
//Call your webservice here.
$http.get("http://jsonplaceholder.typicode.com/posts/1")
.success(function (response) {
console.log(JSON.stringify(response));
});
};
});
httpCallOnAngularError.controller('exceptionTestCtrl', function ($scope) {
throw {message: 'Log this error by calling webservice.'};
});
You can verify this by this template.
<div ng-app="exceptionTestApp" ng-controller="exceptionTestCtrl">
</div>
Webservice call in Exception Handler $http in $exceptionHandler

AngularJS use custom services in custom providers

I have a simple question about the dependency injection in Angular. I create custom services in order to use them within each other. Unfortunately I receive errors the way I was trying it. This is my Code:
var myApp = angular.module('app', []);
myApp.service('$service1', ['$rootScope', function($rootScope) {
this.test = function() {
console.log('service1');
};
}]);
myApp.provider('$service2', ['$service1', function($service1) {
var service = 'service2';
this.registerService = function(mytext) {
service = mytext;
};
this.$get = function() {
var that = {};
that.test = function() {
console.log(service);
};
return that;
};
}]);
myApp.config(['$service2Provider', function($service2Provider) {
$service2Provider.registerService('changed service2');
}]);
myApp.controller('AppCtrl', ['$rootScope', '$service1', '$service2',
function($rootScope, $service1, $service2) {
$service1.test();
$service2.test();
}]);
Error: [$injector:modulerr] Failed to instantiate module app due to:
[$injector:unpr] Unknown provider: $service1
http://errors.angularjs.org/1.2.0-rc.2/$injector/unpr?p0=%24service1
If you remove the dependency of $servic1 in $service2 it will work, but why?
The code is mostly right, except you have to inject service dependencies in $get, not in the provider constructor function, like this:
myApp.provider('$service2', function() {
var service = 'service2';
this.registerService = function(mytext) {
service = mytext;
};
this.$get = ['$service1', function($service1) {
var that = {};
that.test = function() {
console.log(service);
};
return that;
}];
});
It appears that provider can not inject such a dependency. If you rewrite $service2 using a factory, it works:
myApp.factory('$service2', ['$service1', function($service1) {
var that = {};
that.test = function() {
$service1.test();
console.log('service2');
};
return that;
}]);
See this plunker: http://plnkr.co/edit/JXViJq?p=preview
Also I believe that service names starting with a $ a reserved for AngularJS and its extensions. Use names without the $ at the beginning for services defined by your application.

Resources