Scope variable AngularJS [duplicate] - angularjs

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).

Related

How to access $rootScope value out a service function [duplicate]

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) {
}

$rootScope.$emit used in $http callback [duplicate]

This question already has answers here:
Why are Callbacks from Promise `.then` Methods an Anti-Pattern
(2 answers)
Why are AngularJS $http success/error methods deprecated? Removed from v1.6?
(2 answers)
Closed 4 years ago.
I understand the basic Javascripts callbacks, but I do not know what $rootScope.$emit 'dispatchQuery' is doing.
(function() {
angular.module('sp').factory('Object', [
'$rootScope', function($rootScope) {
var Object;
return Object = {
load: function(callback) {
return $http(method: "get", url: "http://myhost/bananas", options = {}).success(function(response) {
$rootScope.myItems = response.items;
return callback && callback();
});
}
};
}
]);
}).call(this);
it is called from main.js
sp.run [
'$rootScope','Object'
, function($rootScope, Object) {
Object.load = function(){ $rootScope.$emit 'Query'}
}]
$rootScope.$emit() dispatches event messages upward through the scope chain. Since $rootScope is at the top of the scope chain, only listeners on $rootScope will receive the event. Somewhere in your code, there should be a $rootScope.$on('Query', function(){...})
However, the syntax of your code seems wrong. The code below will generate a syntax error.
$rootScope.$emit 'Query'
Also, your factory creates a .load() method which is then replaced with a different method in your .run() block. Nowhere in your code sample is either method actually called.
Finally...you should avoid using the keyword Object. Consider giving your service factory a more meaningful name.

Angularjs - Cannot read property 'then' of undefined [duplicate]

This question already has answers here:
AngularJs error Cannot read property 'then' of undefined
(4 answers)
Closed 5 years ago.
I'm new to angularjs, and I know there are a lot of questions regarding this error,
Unfortunately I couldn't find an answer that fits my problem in any of them.
I've got a factory that holds all the functions, and controllers that use them. in one controller I got a GET function that returns an array, most of my functions are written almost the same, as well as functions that's written exactly the same like this one, only with different variables names/url, but this error occurs only with this function:
Controller:
$scope.getAllFunction = function(){
appServicesProvider.getAll($scope.var1).then(function(res){
$scope.var2 = res;
})
};
Factory (appServicesProvider) :
function getAll(var1){
$http.get(restURL+var1).then(
function(response){
return [].concat(response.data.var2)
}
);
}
As I said, there are more functions that's written exactly the same, only this one won't work, which makes it harder for me to solve.
Appreciate any help given!
You have to return the promise
function getAll(var1){
return $http.get(restURL+var1).then(
function(response){
return [].concat(response.data.var2)
}
);
}
Or you can rewrite your factory to return an object containing your resolved promise using $q
app.factory('appServicesProvider', function() {
return {
getAll: function(var1) {
var defer = $q.defer();
$http.get(restURL + var1).then(function(response) {
defer.resolve([].concat(response.data.var2));
}).catch(function(response, status) {
defer.reject(response.data.message);
});
return defer.promise;;
}
}
});

Execute some angular code in the browser console [duplicate]

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;
});

How to call $http request [duplicate]

This question already has an answer here:
Unexpected request: GET No more request expected at $httpBackend
(1 answer)
Closed 7 years ago.
I am trying to make a demo of $http request and test that service also..I do like this
.controller('cntrl',function($scope,appfactory,$http){
$scope.data=[];
appfactory.setValue('test abc');
$scope.getData=function(){
$http.get('data.json').success(function(data){
console.log(JSON.stringify(data))
$scope.data=data;
}).error(function(data){
console.log(JSON.stringify(data))
})
}
$scope.getData();
$scope.toggle=function(){
if(appfactory.mode()=='a'){
$scope.message='naveen'
}else {
if(appfactory.mode()=='b'){
$scope.message='parveen'
}
}
}
})
I load that data from json file and display it on view..But when I try to test that application ..I got error why ? how to remove that error
beforeEach(inject(function($rootScope,$controller,appfactory,_$httpBackend_) {
$scope = $rootScope.$new();
$httpBackend=_$httpBackend_;
createController = function() {
return $controller('cntrl', {'$scope' : $scope });
};
}));
it("tracks that the spy was called", function() {
var response=[{"name":"naveen"},{"name":"parveen"}]
$httpBackend.expectGET('data.json').respond(response);
var controller = createController();
$scope.getData();
$httpBackend.flush();
expect($scope.data[0].name).toEqual('naveen')
});
})
here is my code
http://plnkr.co/edit/zdfYdtWbnQz22nEbl6V8?p=preview
http call to get data is effectively getting called twice in the test. One is when the controller is initialized (because you're calling $scope.getData()) and the second is when you manually call $scope.getData() in the spec.
And your expectation is only mocked once (before controller initialisation). To fix the test (to mimic what the controller is actually doing), the expectation has to be set once more before $scope.getData() is called.
See plunker: http://plnkr.co/edit/eLPOZTCgkSfoACLJsVZo?p=preview
OR
You can replace the expectGET with whenGET which doesn't fail the test if the resource is not called. BUT since you're expecting expect($scope.data[0].name).toEqual('naveen') where 'naveen' comes from the http respose, that change should be fine.

Resources