wifiservice.js:
angular.module('app.WifiServices', [])
.factory('WifiService', function(){
var unique_array = angular.fromJson('[]');
function win_wifi(e){
alert("Success");
}
function fail_wifi(e){
alert("Error");
}
function connectWifi(wifi_ssid){
WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
}
function listHandler(a){
var network_array = [];
for(var i=0; i<a.length; i++){
network_array.push("SSID: " + a[i].SSID + " Signal: " + a[i].level);
}
unique_array = network_array.filter(function(elem, pos) {
return network_array.indexOf(elem) == pos;
});
// alert("Wifi List Ready!");
}
function getScanResult(){
WifiWizard.getScanResults(listHandler, failNetwork);
}
function successNetwork(e){
window.setTimeout(function(){
getScanResult();
}, 3000);
}
function failNetwork(e){
alert("Network Failure: " + e);
}
window.setTimeout(function(){
WifiWizard.startScan(successNetwork, failNetwork);
}, 1000);
return {
list: function(){
return unique_array;
},
connectionToWifi: function(name){
connectWifi(name);
}
};
});
My whole controller:
app.controller('WifiController', ['$scope', 'WifiService', function($scope, WifiService) {
$scope.wifiList = [];
window.setTimeout(function() {
$scope.wifiList = WifiService.list();
// alert($scope.wifiList);
$scope.$apply();
}, 5000);
$scope.getList = function() {
$scope.wifiList = WifiService.list();
return $scope.wifiList;
}
$scope.connectWifi = function(name) {
WifiService.connectionToWifi(name);
}
$scope.checkin = function() {
$scope.getList()
.then(function(result) {
console.log(result);
});
}
}]);
What I am trying to do is, to call the $scope.getList(), which returns a list of the surrounding wifi SSIDs, then within $scope.checkin() I would like to process those data.
Since scanning needs some time I have to wait the getList function to finish, thats Why I am trying to use .then, but it gives me the error says on the title. Any ideas?
How to create a AngularJS promise from a callback-based API
To create an AngularJS promise from a callback-based API such as WifiWizard.connectNetwork, use $q.defer:
function connectWifi(wifi_ssid) {
var future = $q.defer();
var win_wifi = future.resolve;
var fail_wifi = future.reject;
WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
return future.promise;
};
The above example returns a $q Service promise that either resolves or rejects using the callbacks from the API.
Well, I came up with something different:
var unique_array = [];
$scope.wifiList = [];
$ionicLoading.show({
template: "Scanning surrounding AP's..."
});
window.setTimeout(function() {
$scope.wifiList = WifiService.list();
// alert($scope.wifiList);
while ($scope.wifiList == []) {
console.log('Scanning...');
}
$scope.$apply();
$ionicLoading.hide();
}, 5000);
What I realize is that the scanning starts once I load the view. So, I added an IonicLoader to force the user to wait, and not be able to press any buttons till the scan is finished. So no function shall wait one another. Not quite code-wise correct, but it does what I need.
Related
I need to process responses of two different $http requests. What is the best way to do so, knowing that I have to wait for answers of both request before to process their results.
I think I must use something like async, promise, await features, but I cannot figure out how to do so.
var app = angular.module('Async', []);
app.controller('async', function($scope, $http, $timeout, $interval) {
$scope.getCamionTypes = function() {
$http.get("../services/getCamionTypes.php")
.then(function mySucces(response) {
$scope.camionTypes = response.data;
}, function myError(response) {
camionTypes = [];
});
} ;
$scope.getParametres = function() {
var b = $http.get("../services/getParametres.php")
.then(function mySucces(response) {
$scope.parametres = response.data;
}, function myError(response) {
$scope.parametres = [];
});
}
//I make here the first call
$scope.getCamionTypes();
//I make here the second call
$scope.getParametres();
//The following instruction must wait for the end of the 2 calls
console.log('Types de camion : ' + $scope.camionTypes + '\n' + 'Parametres : ' + $scope.parametres);
})
check this
let promise1 = $http.get("../services/getParametres.php");
let promise2 = $http.get("../services/getParametres.php");
$q.all([promise1, promise2]).then(result=>{
//console.log('Both promises have resolved', result);
})
Use Promise.all for such use cases. Promise.all takes an array of promises and gets resolved when both the promises are resolved. It will fail if any of the promises fail.
$scope.getCamionTypes = function() {
return $http.get("../services/getCamionTypes.php")
} ;
$scope.getParametres = function() {
return $http.get("../services/getParametres.php")
}
Promise.all([$scope.getCamionTypes(), $scope.getParametres()]).then(resp => {
//resp[0] and resp[1] will contain data from two calls.
//do all your stuff here
}).catch()
Thank you very much Samira and Shubham for your usefull help !
Here the code modified thank to your advises with the less impact on the architecture of my application.
Best regards.
var app = angular.module('Async', []);
app.controller('async', function($scope, $http, $timeout, $interval, $q) {
$scope.getCamionTypes = function() {
let promise = $http.get("https://www.alphox.fr/ModulPierres_dev/services/getCamionTypes.php")
promise.then(function mySucces(response) {
$scope.camionTypes = response.data;
}, function myError(response) {
camionTypes = [];
});
return promise;
} ;
$scope.getParametres = function() {
let promise = $http.get("https://www.alphox.fr/ModulPierres_dev/services/getParametres.php")
promise.then(function mySucces(response) {
$scope.parametres = response.data;
}, function myError(response) {
$scope.parametres = [];
});
return promise;
}
//I make here the first call
let promise1 = $scope.getCamionTypes();
//I make here the second call
let promise2 = $scope.getParametres();
$q.all([promise1, promise2]).then (result=>{
//The following instructions wait for the end of the 2 calls
console.log('Types de camion : ');
console.log($scope.camionTypes);
console.log('Parametres : ');
console.log($scope.parametres);
$scope.both = {camionTypes: $scope.camionTypes, parametres: $scope.parametres}
});
});
I want to watch changes in my services like in my system logs when there's someone who login the getlogs function must trigger how to achieve this ???
dashboard.controller
function getLogs() {
return dataservice.getLogs().then(function (data) {
vm.logs = data;
return vm.logs;
});
}
dataservice.js
function getLogs() {
return $http.get('/api/timeLogs')
.then(success)
.catch(fail);
function success(response) {
return response.data;
}
function fail(e) {
return exception.catcher('XHR Failed for getPeople')(e);
}
}
I've tried this but its not working
$scope.$watch('dataservice.getLogs()', function () {
getLogs();
}, true);
This is a case for observable pattern where you subscribe for changes on your service
app.service('dataservice', function($http) {
var subscribers = [];
var addSubscriber = function(func){
subscribers.push(func);
}
var notifySubscribers = function(){
for(var i = 0; i< subscribers.length; i++){
subscribers[i](); //invoke the subscriber
}
};
var addLog = function(){
//let's say that the logs are added here
//then notify the subscribers that a new log has been added
notifySubscribers();
};
var getLogs = function() {
return $http.get('/api/timeLogs')
.then(success)
.catch(fail);
function success(response) {
return response.data;
}
function fail(e) {
return exception.catcher('XHR Failed for getPeople')(e);
}
};
return {
addSubscriber: addSubscriber,
addLog: addLog,
getLogs: getLogs
}
});
Then in your controller add a subscriber function to the service
dataservice.addSubscriber(function(){
console.log('new log added');
dataservice.getLogs();
});
NOTE: this can also be done with the RxJs library
if you want to check and get data's change from server, watching a service is not for that, use a polling service.
you check for every 1sec (for example) from a server:
example:
$interval(function() {
dataservice.getLogs().then(function(data) {
vm.logs = data;
});
}, 1000);
or much better:
getLogs = function () {
dataservice.getLogs().then(function(data){
vm.logs = data;
$timeout(getLogs, 1000)
});
}
UPDATE:
I decided that using the JS Module Pattern was not "keeping it simple", so I scrapped it and used jQuery's deferred object to return the data I was looking for. What I really needed was to simply load a JSON file and populate an object. I was just trying to be too fancy by incorporating the JS Module Pattern.
Many thanks to #kiramishima for the correct answer.
Below is the finished code:
function getData(){
var url = CONTEXT + "/json/myJsonFile.json";
return $.getJSON(url);
}
getData()
.done(function(data){
myGlobalObj = data;
})
.fail(function(data){
console.log("fetching JSON file failed");
});
I think I'm getting a little too fancy for my own good here. I'm loading a JSON file and trying to return the API via JS module pattern. Problem is that I believe I'm not implementing the promise correctly and I don't know how to fix it.
Here's my JSON:
{
"result": {
"one": {
"first_key":"adda",
"second_key":"beeb",
"third_key":"cffc"
},
"two": {
"first_key":"adda",
"second_key":"beeb",
"third_key":"cffc"
}
}
}
And here's my JS Module implementation:
var data = (function() {
var url = "/json/dummy.json";
var getAllData = function() {
return $.getJSON(url, function(result){});
};
var promise = getAllData(); // the promise
return {
getFirstObjSecondKey:function() {
return promise.success(function(data) {
return data.result.one.second_key;
});
},
getSecondObjThirdKey:function() {
return promise.success(function(data) {
return data.result.two.third_key;
});
},
};
})();
The problem is that "getAllData()" is coming back as undefined and I'm not sure why; that method returns a Promise that I should be able to handle in the "done" function. How far off am I?
Thanks for any helpful input. This is the first time I'm messing with the JS Module Pattern.
I dont know what is your problem, but I test with:
var getAllData = function() {
return $.getJSON('/json/dummy.json', function(result){})
}
getAllData().done(function(data){ console.log(data.result.one.second_key) }) // prints beeb
works fine in that case, but if try this:
var data = (function() {
var url = '/json/dummy.json';
var getAllData = function() {
return $.getJSON(url, function(result){});
};
return {
getFirstObjSecondKey:function() {
getAllData().done(function(data) {
return data.login;
});
},
getSecondObjThirdKey:function() {
getAllData().done(function(data) {
return data.name;
});
},
};
})();
data.getFirstObjSecondKey returns undefined, then can u pass anonymous function:
var data = (function() {
var url = '/json/dummy.json';
var getAllData = function() {
return $.getJSON(url, function(result){});
};
return {
getFirstObjSecondKey:function(callback) {
getAllData().done(function(data) {
callback(data.result.one.second_key);
});
},
getSecondObjThirdKey:function(callback) {
getAllData().done(function(data) {
callback(data.result.two.third_key);
});
},
};
})();
var t;
data.getFirstObjSecondKey(function(data){
//data should contain the object fetched by getJSON
console.log(data); // prints beeb
t = data; // assign t
})
console.log(t) // prints beeb
Other solution, return always the deferred object
kiramishima's answer works, but it mixes callbacks with Promises. If you're using promises, you should try not to mix both styles.
You have to return a Promise from your functions. Remember that promises can be chained, that is, if you return a Promise from the done function, that becomes the new Promise
var data = (function() {
var url = "/json/dummy.json";
var getAllData = function() {
return $.getJSON(url, function(result){});
};
return {
getFirstObjSecondKey:function() {
return getAllData().done(function(data) {
return new Promise(function(resolve, reject){
resolve(data.result.one.second_key);
});
});
},
getSecondObjThirdKey:function() {
return getAllData().done(function(data) {
return new Promise(function(resolve, reject){
resolve(data.result.one.third_key);
});
});
},
};
})();
data.getFirstObjSecondKey().done(function(secondKey) {
console.log('Second key', secondKey);
});
I am trying to write a loop which performs a number of http requests and adds each response to a list.
However, I don't think I am going about it quite the right way.
I think I am not implementing the required promises correctly. The console log after the for loop shows myList array as empty.
Code:
var _myList = []
function getStuff() {
var deferred = $q.defer()
var url = someUrl
$http.get(url).success(function(response) {
if ( response.array.length > 0 ) {
// loop starts here
for ( var i=0; i < response.array.length; i++ ) {
getThing(response.array[i].id);
};
// check the varibale here
console.log(_myList);
deferred.resolve('Finished');
} else {
deferred.resolve('No stuff exists');
};
}).error(function(error) {
deferred.reject(error);
});
return deferred.promise;
};
function getThing(thindId) {
var deferred = $q.defer()
var url = someUrl + thingId;
$http.get(url).success(function(response) {
_myList.push(response);
deferred.resolve(response);
}).error(function(error) {
deferred.reject(error);
});
return deferred.promise;
};
You can simplify your code as follows:
var allThings = response.array.map(function(id){
var singleThingPromise = getThing(id);
//return a single request promise
return singleThingPromise.then(function(){
//a getThing just ended inspect list
console.log(_myList);
})
});
$q.all(allThings).then(function(){
//only resolve when all things where resolved
deferred.resolve('Finished');
}, function(e){
deferred.reject('Something went wrong ' + e);
});
You indeed won't be able to populate _myList array with for-loop like you set up. Instead create an array of promises - one per data item in response.array and return it as inner promise.
function getStuff() {
var url = someUrl;
return $http.get(url).then(function(response) {
if (response.data.array.length > 0) {
return $q.all(response.data.array.map(function(data) {
return getThing(data.id);
}));
} else {
return 'No stuff exists';
}
});
}
function getThing(thindId) {
var url = someUrl + thingId;
return $http.get(url).then(function(response) {
return response.data;
});
}
After that you would use getStuff like this:
getStuff().then(function(myList) {
console.log(myList);
});
I am implementing long polling to know the state of some long running event on the server side. I create my own factory that will notify me when a server event triggers. Here is the factory.
.factory("$httpPolling", function ($http) {
function $httpPolling($httpService) {
var _responseListener, _finishListener;
var cancelCall = false;
var _pollId;
function waitForServerCall(id) {
console.log("executing waitForServerCall");
$httpService.get(href("~/polling/" + id))
.success(function (response) {
var cancelPolling = _responseListener(response);
if (cancelPolling || cancelCall) {
return;
}
else {
waitForServerCall(id);
}
});
};
function _sendData(httpMethod, url) {
var pollingId = guid();
_pollId = pollingId;
if (url.split("?").length == 2) {
url += "&pollid=" + pollingId;
}
else {
url += "?pollid=" + pollingId;
}
if (httpMethod == 0) {
$httpService.get(url).success(function (response) {
if (_finishListener) {
_finishListener(response);
}
cancelCall = true;
});
}
else {
$httpService.post(url).success(function (response) {
if (_finishListener) {
_finishListener(response);
}
cancelCall = true;
});
}
}
var $self = this;
this.get = function (url) {
_sendData(0,url);
return $self;
};
this.post = function (url) {
_sendData(1, url);
return $self;
};
this.listen = function (_listener) {
_responseListener = _listener;
waitForServerCall(_pollId);
return $self;
}
this.finish = function (_finish) {
_finishListener = _finish;
return $self;
}
}
return new $httpPolling($http);
});
Where the sintax of usage should be:
$httpPolling.get("url")
.listen(function(event){
// fires when server event happend
})
.finish(function(response){
// fires when the long running process finish
});
The problem is that _sendData method does not execute asynchronously because the waitForServerCall only executes the ajax call when the _sendData(long running process) method get the response from the server.
Why? Is this an angular behavior?
Angular $httpProvider has an option provided for async http calls, which is set to false as default value.
Try
app.config(function ($httpProvider) {
$httpProvider.useApplyAsync(true);
});