This question already has answers here:
How can I test an AngularJS service from the console?
(4 answers)
Closed 6 years ago.
I have a website builded with angular. I want to do some debugging in the browser console but i don't know how to actually execute my function.
I tried this :
angular.module('app').run(function(myService) {
myService.doSomething();
});
But the function is not called.
This works - Plunker
JS
var app = angular.module('plunker', [])
.run(function(myService) {
myService.doSomething();
})
.factory('myService', function () {
var obj = {};
obj.doSomething = function () {
console.log("Hello world");
}
return obj;
});
Related
This question already has answers here:
How to call a function from another module
(2 answers)
Closed 3 years ago.
I have two angularjs file. I have created some function inside a controller.Now I want to call this function from another module and controller.I tried by injecting the module dependency into my caller module .But it is not recognizing the function.I am new in angularjs.
This is the module I want to call
var app = angular.module("demo", []);
app.controller("testCtrl", function($scope,$http,$window) {
$scope.temp = "";
$scope.rows = []; // init empty array
$scope.datainput =[];
$scope.dataconfig =[];
$scope.myrunner=function(canvasid,inputdata,configdata){
var flag=0;
$scope.datainput=inputdata;
$scope.dataconfig=configdata;
console.log("from base module");
}
$scope.refresh = function(){
location.reload();
}
});
This is the caller module
var app = angular.module("tester", ["demo"]);
app.controller("mycontroller", function($scope) {
var input=[{"status":"PAY_FAIL","value":6248},{"status":"PAY_SUCCESS","value":868},{"status":"PM_REQUESTED","value":11199},{"status":"PAY_INIT","value":992}] ;
var config=[
{"type":"font_name","value":"Calibri"},
{"type":"font_size","value":"25px"}
] ;
$scope.myfn=function(){
demo.myrunner('myCanvas',input,config);
demo.myrunner('myCanvas2',input,config);
}
$scope.myfn();
});
You need to use the factory to communicate between two modules. You cannot have the function inside a controller and call the function from another module.
Example:
var moduleA= angular.module('demo',[]);
moduleA.factory('factoryA', function() {
return {
alertA: function() {
alert('a');
}
};
});
Then use the alertA factory in module B:
angular.module('tester',['A']).controller('mycontroller',function($scope,'factoryA'){
factoryA.alertA();
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am trying to get the value of $rootScope.exists from the SomeService.getData() function.
When I see the rootScope (using console.log) outside the function, I can see the $rootScope.exists value but on printing it, it says its undefined.
How can I get the value?
else {
SomeService.getData().then(function (response) {
$rootScope.1a = response.data;
$rootScope.levels = response.data.levels;
$rootScope.exists = checkAvailability($rootScope.accessLevels, "DataDAta");
});
console.log("sadsad", $rootScope.exists);
if ($rootScope.exists) {
$location.path('/ABC');
}
else {
$location.path('/DEF');
}
}
Did you inject '$rootScope' into your modules array?
app.controller('LoginCtrl', function($rootScope) {
}
This question already has answers here:
AngularJs ReferenceError: $http is not defined
(3 answers)
Closed 4 years ago.
I keep getting the following error:
Cannot read property 'get' of undefined
at Object.getChannelIdFromYoutubeUsername
at Object.vm.creatorAccountCreationFormSubmit
Even though I am injecting $http into my service, and whenever I paste the url being passed into the $http.get command, I get an output in my browser window.
Here is my service:
angular.module('adsomaApp').service('YoutubeService', function($log) {
var url = 'https://www.googleapis.com/youtube/v3';
function getChannelIdFromYoutubeUsername(youtubeApi, youtubeUsername, $http) {
var queryUrl = url + "/channels/?key=" + youtubeApi + "&forUsername=" + youtubeUsername + "&part=id";
return ($http.get(queryUrl).then(handleSuccess, handleError));
}
function handleSuccess(response) {
return response.data;
}
function handleError(response) {
if (!angular.isObject(response.data) || !response.data.message) {
return ($q.reject('An unknown error occurred.'));
}
return ($q.reject(response.data.message));
}
var youtubeService = {
getChannelIdFromYoutubeUsername: getChannelIdFromYoutubeUsername
};
return youtubeService;
});
Here is my controller:
vm.channelId = {};
vm.creatorAccountCreationFormSubmit = function() {
YoutubeService.getChannelIdFromYoutubeUsername(ConstantsService.youtubeSettings().youtubeApiKey, vm.connectYoutubeFormData.youtubeUsername).then(function(succ) {
vm.channelId = succ;
$log.info(vm.channelId);
}, function error(err) {
$log.error('Error: ', err);
});
};
angular.module('adsomaApp').service('YoutubeService', function($log, $http) { }
you didn't inject in service layer so it is showing undefin
Two basic changes:
Inject $http into the Service
angular.module('adsomaApp').service('YoutubeService', function($http, $log) {
Remove $http from the arguments of this service method
function getChannelIdFromYoutubeUsername(youtubeApi, youtubeUsername) {
The issue is that, when this Service Method is being called from the Controller, the third argument is NOT sent by you. Which, basically means, $http will be null.
I have addressed this issue by injecting $http in the service and by excluding the third argument in the method signature.
These two changes should take care of the issue. I have not included rest of the code.
This question already has answers here:
Why is Access-Control-Expose-Headers needed?
(3 answers)
Closed 5 years ago.
I add errorHandlerInterceptor to handle errors as you seen below:
(function() {
'use strict';
angular
.module('rasool')
.config(httpConfig);
function httpConfig($httpProvider) {
$httpProvider.interceptors.push('errorHandlerInterceptor');
}
})();
and in the errorHandlerInterceptor i want to get a specific header from response headers like this:
(function() {
'use strict';
angular
.module('rasool')
.factory('errorHandlerInterceptor', errorHandlerInterceptor);
function errorHandlerInterceptor ($q, toaster, $rootScope, $timeout) {
var service = {
responseError: responseError
};
return service;
function responseError (response) {
var errorHeader = response.headers('X-app-alert');
if(errorHeader) {
// do something
}
return $q.reject(response);
}
}
})();
The problem is that the errorHeader is null, but when i check the response headers with Chrome DevTools, this header exists and have a value as you can see in the below screenshot:
UPDATE
All of these part are running correctly in the website, but i created a copy of html, js and css files to create an ionic1 application, but when i run ionic serve command to test the application, i have this problem.
Did you try to call it like this:
var errorHeader = response.headers();
and after errorHeader should be an object that have the data you need.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a problem about the scope of variables in a Cordova program.
This is my code:
angular.module('starter.services', [])
.factory('myFactory', function ($http) {
var myVar = "HELLO";
alert(myVar); //HELLO -> Correct
$http.get("URL").then(
function (response) {
myVar = response.data;
alert(myVar) // Correct Answer
}, function (error) {
console.log("Get config.json error - " + JSON.stringify(error));
}
);
alert(serverName); //HELLO -> why?
I declared my variable outside the http block. Can you help me? thanks
For one, you have never defined serverName so that will alert undefined.
Your final Alert is also being called before your $http.get() has returned, so myVar hasn't been updated. I think you should read up on the $http service (https://docs.angularjs.org/api/ng/service/$http) and how promises work (http://andyshora.com/promises-angularjs-explained-as-cartoon.html).