Update scope variable from $http.get on JSON - javascript

I'm having an issue with a $scope variable not updated :
In my controller I have :
$scope.frCartoList = [];
$scope.enCartoList = [];
$scope.cartoList = [];
$scope.filteredCartoList = [];
$scope.loadJSON = function () {
$http.get("SVG/fr/cartoList.json")
.success(function (data) {
$scope.frCartoList = data;
})
.error(function () {
console.log("Error while getting french json.");
});
$http.get("SVG/en/cartoList.json")
.success(function (data) {
$scope.enCartoList = data;
})
.error(function () {
console.log("Error while getting english json.");
});
$scope.setDefaultSearch();
$scope.getAreaFilters();
$scope.getBlockFilters();
if ($scope.shared)
$scope.homeVisible = false;
console.log($scope.enCartoList);
};
$scope.setJSON = function () {
if ($scope.isEnglish)
$scope.cartoList = $scope.enCartoList;
else if ($scope.isFrench)
$scope.cartoList = $scope.frCartoList;
console.log($scope.enCartoList);
$scope.initMenu();
$scope.filteredCartoList = $scope.cartoList.filter($scope.search);
};
$scope.loadJSON();
$scope.setJSON();
But my $scope.enCartoList and my $scope.frCartoList have the proper value only inside the $http.get
I suppose, this is not the main $scope that is used or something, but that's weird, because before that I had only one $scope.cartoList I used to set in the $scope.loadJSON and it was updated in the whole controller...

Related

I'm trying to return some data from http request in angular js but it gives an undefined

Here is the controller of angular js that is calling the service to get the hotels
vm.getTopHotels = function(){
var hotelsLimit = 10;
var top_hotels =
dataService.getHotels()
.then(function(hotels){
console.log('adf');
sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC');
hotelDetailsCheck = checkDetailsIfExists(sortHotels);
//Get only top 10 hotels for home page
top_hotels = hotelDetailsCheck.slice(0,10);
vm.topHotels = top_hotels;
},
function(data){
console.log('Failed to get Hotels');
});
};
vm.getTopHotels();
** And here is the dataService that is calling the Http get request to get the data but in the controller, it gives me undefined so is there something wrong in the datsService return method because I think it is not returning **
(function(){
angular
.module('app')
.factory('dataService',DataFactory);
DataFactory.$inject = ['$http','$q']
function DataFactory($http,$q){
var service = {
hotels:[],
getHotels:getHotels,
saveHotels:saveHotels
};
return service;
function saveHotels(){
var def = $q.defer();
$http.get('/hotels/saveHotelsData')
.then(function successCallback(data){
def.resolve(data);
},function errorCallback(data){
def.reject('Something went down :(');
});
return def.promise;
}
function getHotels(){
// var def = $q.defer();
return $http.get('/hotels/getHotelsData')
.then(function successCallback(data){
service.hotels = data;
});
}
}
})();
// ...
.then(function(data) {
console.log('adf');
sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC');
What's hotels? It isn't declared anywhere. If hotels is supposed to be the response from API, then it should be declared so:
.then(function(hotels) {
console.log('adf');
sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC');
Update: your getHotels passes results through a function without return statement, hence will resolve to undefined. Should be
function getHotels(){
return $http.get('/hotels/getHotelsData')
.then(function successCallback(data) {
service.hotels = data;
return data;
});
}

Why "alert" always show the first one?

i dont understand why it is always pop-up the 1st alert no matter what i input it right or wrong. Can you help me take a look at my code and show me what i have done wrong. Thank you very much.
<script>
var myapp = angular.module('myapp', []);
myapp.controller('Alerts', function getAlerts($scope, $http) {
$scope.name = null;
$scope.host = null;
$scope.searchs = [];
$scope.hide = false;
$scope.getSearch = function(name, host) {
$scope.hide = $scope.hide = true;
var data = {
name: name,
host: host
};
var url = "https://h2kgcp144d.execute-api.us-east-2.amazonaws.com/Testing-midterm/rds-search-alert-info";
$http.post(url, data)
.then(
function(response) {
$scope.searchs = angular.fromJson(response.data);
alert('Alerts found!');
//$scope.hide = false;
},
function(error) {
alert('Failed to search!');
//$scope.search = false;
});
};
});
</script>
You set the alert on both success and failure case. If this is what you want, then remove the alert from the success case:
function(response) {
$scope.searchs = angular.fromJson(response.data);
//$scope.hide = false;
},

Passing variable between functions in a service in angularjs

I have been searching for an answer to this, and cannot seem to find anything. I have a service, in the first block I am successfully logging a url that I then need to pass into my getData() function. But it comes back undefined, I have tried the method below, and I tried moving the first $http.get into the controller where I am calling it, as well as moving the first $http.get into the getData() function. Am I going about this all wrong?
di.service('testService', function($http) {
$http.get('https://us.api.data/tichondrius?locale=en_US&apikey=xxxxxxxx').
then(function(response) {
var urlToJsonFileUncut = response.data.files[0].url;
console.log(urlToJsonFileUncut);
urlToJsonFile = urlToJsonFileUncut.slice(7);
console.log(urlToJsonFile);
return urlToJsonFile;
});
this.getData = function(urlToJsonFile) {
console.log(urlToJsonFile);
return $http.get('http://localhost:1337/' + urlToJsonFile).
then(function(response) {
console.log(response.data.realms[0].name);
return response.data.realms[0].name;
});
}});
$http is an async request. so you need to chain it inside the first request to ensure the value of first response is available when second request is called.
di.service('testService', function($http) {
var getData = function () {
return $http.get('https://us.api.data/tichondrius?locale=en_US&apikey=xxxxxxxx').
then(function(response) {
var urlToJsonFileUncut = response.data.files[0].url;
console.log(urlToJsonFileUncut);
var urlToJsonFile = urlToJsonFileUncut.slice(7);
console.log(urlToJsonFile);
$http.get('http://localhost:1337/' + urlToJsonFile).
then(function(response) {
console.log(response.data.realms[0].name);
return response.data.realms[0].name;
});
});
}
return { getData: getData; }
});
I would suggest you to use a factory instead of a service
Check out the below code
di.factory('testService', function ($http) {
var variable_name;
var serviceMethodName = function () {
$http.get('https://us.api.data/tichondrius?locale=en_US&apikey=xxxxxxxx').
then(function (response) {
var urlToJsonFileUncut = response.data.files[0].url;
console.log(urlToJsonFileUncut);
urlToJsonFile = urlToJsonFileUncut.slice(7);
console.log(urlToJsonFile);
variable_name = urlToJsonFile; //added
});
}
//modified parameter in below method
var getData = function (variable_name) {
var urlToJsonFile = variable_name; //added
console.log(urlToJsonFile);
return $http.get('http://localhost:1337/' + urlToJsonFile).
then(function (response) {
console.log(response.data.realms[0].name);
return response.data.realms[0].name;
});
}
//Exposes the two methods and accessbile through out the app unless it is modified
return {
serviceMethodName: serviceMethodName,
getData:getData
}
});

Cannot read property 'toLowerCase' of undefined (Angularjs/JavaScript/Json)

I'm building Angular/Express app, I load data with controller and try to work with data in a function but I get error in console
Cannot read property 'toLowerCase' of undefined
When I manually write JSON data it works just fine.
Anyone had this error and why is it happening?
Edit: Also I want function to work on click, when I want it not when it's loaded, also I use data from listData in view so I know it's loaded
Controller
var self = this;
self.listData = [];
var self = this;
self.listData = [];
$http.get('/myList')
.success(function (data) {
self.listData = data;
console.log(data);
})
.error(function (data) {
console.log('Error: ' + data);
});
self.myFunc = function(){
var map = self.listData.reduce(function (p, c) {
p.set(c.name.toLowerCase(), c.surname);
return p;
}, new Map());
console.log(...map);
}
HTTP.GET is an asynchronous function
You could call your function which turns the data to lowercase in the .success of your http.get. That way you know that the data has arrived. Now you might be executing this function a bit too early which means that you do not yet have the data in your list.
If you try to run the toLowerCase() on your data, before you actually retrieved the data you will get this error. That is one of the things you learn to deal with when working with web requests.
For example writing your code like this would work.
$http.get('/myList')
.success(function (data) {
self.listData = data;
myFunc(listData);
console.log(data);
})
.error(function (data) {
console.log('Error: ' + data);
});
}
function myFunc(){
var map = self.listData.reduce(function (p, c) {
p.set(c.name.toLowerCase(), c.surname);
return p;
}, new Map());
console.log(...map);
}
Here is your updated code works on click of an element:
jQuery("#a-div-to-click").on("click", function() {
var self = this;
self.listData = [];
$http.get('/myList').success(function (data) {
self.listData = data;
console.log(data);
self.myFunc();
}).error(function (data) {
console.log('Error: ' + data);
});
}
self.myFunc = function(){
var map = self.listData.reduce(function (p, c) {
p.set(c.name.toLowerCase(), c.surname);
return p;
}, new Map());
console.log(map);
}
});
V2) The data is loaded at "onload" phase and the process done at "onclick" phase:
app.controller('yourController', function ($scope, $http) {
$scope.fetchData = funcion(onSuccess) {
$http.get('/myList').success(function (data) {
$scope.aDivlistData = data;
console.log(data);
if (onSuccess != null) {
onSuccess();
}
}).error(function (data) {
console.log('Error: ' + data);
});
}
}();
$scope.onADivClicked = function() {
if ($scope.aDivlistData == null) {
$scope.fetchData($scope.populateMap);
} else {
$scope.populateMap();
}
};
$scope.populateMap = function() {
var map = $scope.aDivlistData.reduce(function (p, c) {
p.set(c.name.toLowerCase(), c.surname);
return p;
}, new Map());
console.log(map);
}
}
//html part:
//<div id="a-div-to-click" ng-click="onADivClicked()">A Div</a>
Just by looking at your code. It looks like "c.name" is undefined. May be you can print that variable out and see what's in it
c.name is undefined for some item in your listData. Checkout JSON which you receive from server, not faked one.
NOTE: $http.get is asynchronous.
Putting self.myFunc = ... into success handler of $http.get suppose to give correct behaviour. You can take a look on Understanding Asynchronous Code in Layman's terms to see how async works.
Good Luck ! :)

undefined function in timeout angularjs

I have the following controller :
app.controller('ListeSASController', function($scope, $rootScope, $routeParams, $location, userService, RefreshSASServices, $timeout){
this.IsUserLogged = function()
{
return userService.user().isLogged;
};
var promise = $timeout(RefreshSASServices.RafraichirSAS(), 100);
this.getSAS = function(){
return RefreshSASServices.getSAS();
};
$scope.$on('$locationChangeStart', function(){
RefreshSASServices.ArreterLesRafraichissements();
});
});
with the following service :
app.service('RefreshSASServices', function($http, userService, serverConfigService, $q, $timeout, $translate, constantsServices) {
var listeSAS = [];
var $this = this;
var promiseRefreshSAS;
// Getters
this.getSAS = function()
{
return listeSAS;
};
//Setters
this.clearDatas = function()
{
listeSAS = [];
};
// Communication with the server
$this.getServerUri = function()
{
return serverConfigService.getServerUri()+"majsvc/";
};
// Fonctions de rafraichissement
$this.ArreterLesRafraichissements = function()
{
if(promiseRefreshSAS !== undefined)
$timeout.cancel(promiseRefreshSAS);
};
$this.GetSASFromServer = function()
{
var promises;
if(userService.user().isLogged)
{
var uri = $this.getServerUri() + "getAllSAS/"+userService.user().UserObject._id;
promises = $http.get(uri)
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
return data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return "";
});
}else{
promises = $q.when(!userService.user().isLogged)
}
return promises;
};
$this.RafraichirSAS = function () {
// functions that call
$this.GetSASFromServer()
.then(function(promise){
if(promise !== undefined && promise.data !== undefined)
{
listeSAS = promise.data;
//alert('refreshing the SAS list:' + JSON.stringify(listeSAS));
}else listeSAS = [];
promiseRefreshSAS = $timeout($this.RafraichirSAS, 3000);
})
.catch(function(error)
{
console.error("Error :", error);
promiseRefreshSAS = $timeout($this.RafraichirSAS, 7000);
});
};
});
When I load my page using routes :
.when('/listeSAS', {
templateUrl : './includes/sas/liste_sas.html',
controller : 'ListeSASController',
controllerAs : 'controller'
})
everything works fine, if my data changes on the server it gets updated on the UI, My UI is also displaying what I want. Everything is OK except that when the pages loads I get the following error :
TypeError: undefined is not a function
at file:///includes/libs/angular.js:14305:28
at completeOutstandingRequest (file:///includes/libs/angular.js:4397:10)
at file:////includes/libs/angular.js:4705:7
which is the function "timeout" of angular, and the line 14305 is :
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
finally {
delete deferreds[promise.$$timeoutId];
}
Why angular is throwing this exception ? What did I do wrong ?
To be known :
On my login page I set 2 timeouts which I don't stop because they refresh "global" variables such as the number of private messages. Despite the error both timeout are still working.
I use node webkit with my application and it crashes maybe one in three times when I open this route (after 5-10 seconds).
Thank you for your help.
Is it that you're calling RafraichirSAS(), which returns undefined instead of passing in the function?
E.g, instead of
$timeout(RefreshSASServices.RafraichirSAS(), 100);
Do
$timeout(RefreshSASServices.RafraichirSAS, 100);

Categories