i am using $timeout in my controller but its not working!
app.controller("Friendsrequests",['$http','$log','$location','$timeout','$scope', function($http,$log,$location,$timeout,$scope){
//getting base url of application
this.baseUrl = function() {
var base_url = window.location.origin;
var pathArray = window.location.pathname;
return base_url;
// return base_url+pathArray;
};
// assigning to a variablebase_url('login/f_request');
var ThroughUrl = this.baseUrl()+'/keon/login/f_request';
//declare a variable
var ata = this;
ata.notifications = [ ] ;
ata.counts=' ';
//sending ajax request
function getNotifications()
{
$http({method: 'POST', url: ThroughUrl,})
.success(function(data) {
// this callback will be called asynchronously
// when the response is available
//assign data to the variable
ata.notifications=data;
ata.counts =data.length;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
$timeout(function() {
getNotifications();
}, 1000);
}]);
what is the issue .
UPDATED
Just replace
$timeout(function() {
getNotifications();
}, 1000);
with
$interval(function() {
getNotifications();
},1000);
Check Angular's doc
while calling timeout in angularJS just remove Parentheses or brackets ()
$timeout(getNotifications, 1000);
getNotifications function will call after 1000 milliseconds(One second)
Related
i want to refresh/reload the method in every 30 seconds. but im not able to send the variable data to another function i.e setInterval.how to pass variable in the setInterval method.while adding static variable its working but how can i pass the id to setInterval method
var app = angular.module('PIR_Detection', []);
app.controller('myCtrl', function ($scope, $http, $window) {
$scope.sel_val = 0;
$scope.DefaultLabel = "Loading.....";
var post = $http({
method: "get",
url: "../data.json",
dataType: 'json',
data: {},
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$scope.Customers = data;
});
post.error(function (data, status) {
});
$scope.getPIRData = function (id) {
var url = "/PIRDetails/GetPIRStatus/" + id;
$http.get(url)
.then(function (response) {
$scope.myWelcome = response.data;
$scope.pirstatus = base64toHEX($scope.myWelcome.dataFrame);
$scope.timestamp = getIST (response.data.timestamp);
$scope.rssi = response.data.rssi;
deviceid = id;
});
};
setInterval(function () {
$scope.getPIRData("100010102");//unable to pass id here
}, 30000)
});
you can do it in various way,
example:
//set data
window.deviceId=Id
and use it in settimout
setInterval(function () {
$scope.getPIRData(window.deviceId);//unable to pass id here
}, 30000)
but you can declare any global variable of the settimeout outer scope, then that variable will be available into the settimeout call back function, because then it will be treated as Closures
Courtesy of #tvanfosson:
You probably want to have a function that creates the interval timer for you. Pass in the parameter to the function so its value is captured in the function closure and retained for when the timer expires.
function createInterval(f,dynamicParameter,interval) { setInterval(function() { f(dynamicParameter); }, interval); }
Then call it as createInterval(funca,dynamicValue,500); Obviously you can extend this for more than one parameter. And, please, use more descriptive variable names. :)
I have a problem with my script which collects data from database in parts. I would like to inform Angular when downloading data is finished so I used $watch. Unfortunatelly, it does not work. Angular calls function at the beginning instead of after change loadingComplete value.
angular
.module('app')
.controller('tlmController', function($scope, $http) {
var vm = this;
var data = [];
vm.countTestLines = 0;
vm.loadingComplete = false;
$scope.$watch('vm.loadingComplete', function() {
console.log(data);
});
$http({
method: 'GET',
url: 'app/server/tt/count_testlines.php'
}).then(function successCallback(response) {
vm.countTestLines = parseInt(response.data.count);
downloadInParts(data, 0, vm.countTestLines);
}, function errorCallback(response) {
console.log('error');
});
var downloadInParts = function(data, offset, max) {
if(max < offset) {
vm.loadingComplete = true;
return;
}
$http({
method: 'GET',
url: 'app/server/tt/get_testlines.php',
params: { offset: offset }
}).then(function successCallback(response) {
data = data.concat(response.data);
downloadInParts(data, offset + 5, max);
}, function errorCallback(response) {
console.log('error');
});
}
});
The problem is that the loadingComplete is not a part of the scope. you should declare it as $scope.loadingComplete;.
Since you are using 'vm' instead of '$scope', it is a necessary that you need to insert $scope.$apply in your function.
if(max < offset) {
vm.loadingComplete = true;
$scope.$apply();
return;
}
$scope always watches for change in value and if there is any, Angular will call the $digest() function internally and the changed value will be updated. Using 'vm' wont update the value which results in your problem.
If you are using var vm = this, which is the proper way according to JohnPapa's styleguide for AngularJS, you should rewrite your $watch to:
$scope.$watch(function(){ return vm.loadingComplete }, function() {
console.log(data);
});
Update from comments:
Your function parameter data hides your data variable from your controller.
I'm trying to get data from a server in my AngularJS app, using $http.get. But when I execute the request, it seems to get cancelled by something. It happens with every link I use. Local files are working.
Below the code from Controller.js:
angular
.module('schoolApp')
.controller('configController', [
'apiService', '$http', function (apiService, $http) {
var vm = this;
vm.isActive = isActive;
vm.addPortal = addPortal;
...
function addPortal() {
...
apiService.getServerData('someUrl', "1.0")
.then(function (result) {
var test = result.data;
})
.catch(function (result) {
console.log(result);
});
}
...
And the Service.js:
angular
.module('schoolApp')
.service('apiService', [ '$http', function ($http) {
var service = {
getServerData: getServerData,
};
return service;
function getServerData(portalUrl, appVersion) {
// var url = "http://../.../.svc/GetSetting?alias=...&AppVersion=1.0";
var url = "http://xml.buienradar.nl";
//var url = "test.json";
//var url = "xml.xml";
// "http://" +
// portalUrl +
// "/.../.../.svc/GetSetting?alias=" +
// portalUrl +
// "&AppVersion=" +
// appVersion;
return $http.get(url);
}
}]);
Executing this code will show the alert("ERROR: " + result) from the controller class. Data from the result:
result: Object config: Object data: null headers: (c)
status: -1 statusText: ""
__proto __: Object
Network in browser shows the call is cancelled:
http://i.stack.imgur.com/MJoZM.png
More info:
- I'm using Phonegap (tested without and doesn't work either)
- AngularJS 1.4
Ok, found the answer. I called window.location.reload() in the same function, and that conflicted. So, now I added it to the .then() function in the request.
I have been at this for over 10 hours at this point. It does not make sense to me. I desperately need clarification on what I'm doing wrong. Below is a simple factory function that makes an AJAX call for a JSON file. There are no async. data issues and everything just works. The issue I'm having is that I'm trying to save the returned result and access it later. If the variable is populated, I don't then have to make a second AJAX call, I can simple grab the contents of a local variable. I realize there are other ways of doing this, but I'm particular to using this factory method.
storyDataAsFactory.$inject = ['$log', '$http', '$q'];
angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($log, $http, $q) {
var storiesCache = [];
function getStories(url) {
url = url || '';
if (url !== '') {
var deferred = $q.defer();
alert('inside getStories, length of storiesCache = ' + storiesCache.length); // this is always zero! Why?
//determine if ajax call has already occurred;
//if so, data exists in cache as local var
if (storiesCache.length !== 0) {
$log.info('Returning stories from cache.');
deferred.resolve(storiesCache);
return deferred.promise;
}
$http({method:'GET', url:url})
.success(function (data, status, headers, config) {
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
} else {
$log.error('(within storyDataAsFactory) Failed to retrieve stories: URL was undefined.');
}
}
return {
stories: storiesCache,
getStories: function(url) {
alert('inside return factory object, length of stories = ' + this.stories.length);
//getStories returns a promise so that routeProvider
//will instantiate the controller when resolved
return getStories(url);
}
};
}
You need to use a promise. I have not ran the code below, but this is the idea:
angular.module('ccsApp').service('storyDataAsFactory', storyDataAsService);
function storyDataAsService($log, $http, $q) {
var storiesCache = [];
function getStories(url) {
url = url || '';
if (url !== '') {
alert('inside getStories, length of storiesCache = ' + storiesCache.length); // this is always zero! Why?
if (storiesCache.length == 0) {
return $http({method:'GET', url:url});
} else {
var deferred = $q.defer();
deferred.resolve(storiesCache);
return deferred.promise;
}
} else {
$log.error('(within storyDataAsFactory) Failed to retrieve stories: URL was undefined.');
}
}
return {
getStories: function(url) {
return getStories(url).then(function(stories) {
// Do whatever
return stories;
});
}
};
}
storyDataAsService.getStories().then(function(stories) {
$scope.stories = stories
})
Ok, please go easy on me as I'm just learning Angular. The following code works but there has to be a better, cleaner, way to do this. I have been reading everything I can and from what I can tell, possibly setting these up in factories might be best?? So far, everything I have tried ends up breaking things but it's probably me doing something incorrectly.
Prerequisites
I need to be able to use this in a module (so I can add additional custom directives I have)
I am making a total of 3 API calls, two are using GET method but one has to use POST method
My code:
$apiUrl = '_includes/gtmetrix.php'; // This is using a local proxy to access remote API.
$apiKey = '';
$gapiUrl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed';
$gapiKey = '1z2x3c4v5b6n7m8a9s';
$gapiStrategy = 'mobile';
$requestUrl = '<?php echo $_POST['url']; ?>';
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'POST';
$scope.url = $requestUrl;
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $apiUrl + '?url=' + $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data || "Request successful";
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.fetch();
$scope.fetchGoogle = function() {
$scope.code = null;
$scope.response = null;
$http({method: 'GET', url: $gapiUrl + '?url=' + $scope.url + '&key=' + $gapiKey, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.datag = data || "Request successful";
}).
error(function(data, status) {
$scope.datag = data || "Request failed";
$scope.status = status;
});
};
$scope.fetchGoogle();
$scope.fetchGoogleMobile = function() {
$scope.code = null;
$scope.response = null;
// $scope.data = '<i class="fa fa-spinner fa-spin"></i>';
$http({method: 'GET', url: $gapiUrl + '?url=' + $scope.url + '&key=' + $gapiKey + '&strategy=' + $gapiStrategy, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.datagm = data || "Request successful";
}).
error(function(data, status) {
$scope.datagm = data || "Request failed";
$scope.status = status;
});
};
$scope.fetchGoogleMobile();
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
I have tried to get this working for days now so any help in the right direction would be greatly appreciated. Thx!
One thing you can do is use the convenient $http.get() and $http.post() methods. Or as Klaster_1 suggested you could look into using $resource. Not sure what your trying to accomplish but it looks like you have some unnecessary code. I might start with something like this and add in more as necessary.
function FetchCtrl($scope, $http) {
var googleApiBaseUrl = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=<?php echo $_POST['url']; ?>&key=1z2x3c4v5b6n7m8a9s";
$http.post("_includes/gtmetrix.php?url=<?php echo $_POST['url']; ?>")
.success(function(data) {
$scope.data = data;
});
$http.get(googleApiBaseUrl)
.success(function(data) {
$scope.datag = data;
});
$http.get(googleApiBaseUrl + "&strategy=mobile")
.success(function(data) {
$scope.datagm = data;
});
}
Here's what I do. I'm using $resource instead of $http, but it should be enough to get you going. You may even want to use the $resource since it has the built-in functions.
My Factory fns.
.factory('WorkOrder', function($resource){
// $resource Usage: $resource(url[, paramDefaults][, actions]);
return $resource('/controller/get/:id.json', {}, {
/*
* By default, the following actions are returned; modify or add as needed
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'delete': {method:'DELETE'} };
*/
});
})
My Controller.
// get the work order data using the work order id from the tag attribute
var getWO = function() {
WorkOrder.get({woId:$attrs.id},
// success callback
function(response) {
// Assign the work order data to the scope
$scope.WorkOrder = response.WorkOrder;
},
// fail callback
function(response) {
// whatever...
}
);
};
getWO();
I put my success and fail fns in my controller because that's where I most likely know how I want to respond to success or failed calls. I also assign the function to a variable and then call it right after in case I want to include the fn call inside a $timeout or call it elsewhere.
You can create as many factory fns as you want. If there's a dependency between factory fn calls, then you can put the dependent call within your success callback of your controller.
Hope this answers your question.