Handling multiple ajax call using $q.all - css

I'm trying to call multiple ajax in my page using $q. after all the response am storing in one array. but it seems not working correctly-
My controller-
used for loop to go over multiple pages in API and get the json.
$scope.items = [];
for (var i = 1; i < 10; i++) {
var apiURL = "https://swapi.co/api/planets?page =" + i;
searchData(apiURL).then(function(response) {
$scope.items.push(response[0].data.results);
});
}
$scope.showDetail = function(data) {
$scope.items = data.results;
$scope.items.sort(function(a, b) {
return a.population.localeCompare(b.population);
});
}
$scope.showDetail($scope.items);
$scope.highlighFont = function() {
}
My Factory-
var app = angular.module('starApp');
app.factory('searchData', function($q, $http) {
return function(apiUrl) {
var promises = [];
var deffered = $q.defer();
$http({
method : 'GET',
url : apiUrl
}).then(function(data) {
deffered.resolve(data);
}, function(error) {
deffered.reject();
})
promises.push(deffered.promise);
return $q.all(promises);
}
});
can someone correct me if am doing wrong??

You need to call $q.all() in the controller
app.factory('searchData', function($q, $http) {
return function(apiUrl) {
return $http({
method : 'GET',
url : apiUrl
});//$http returns a promise
}
});
controller:
$scope.promises = [];
for (var i = 1; i < 10; i++) {
var apiURL = "https://swapi.co/api/planets?page =" + i;
$scope.promises.push(searchData(apiURL));
}
$q.all($scope.promises).then(function(results){
console.log(results);
});

Related

asp.net "put" method with angular js

im workin with my website and actually workin with 3 methods-put,post,delete. In my code i did two of them:delete and post and they are correct, but i have no idea how i can do put do edit my TODO list.
That's my code, if you can help me i'll be glad.
Have a nice day.
This is a service .js file
app.factory('reservationService', ReservationService);
function ReservationService($http) {
var CreateReservation = function (reservation) {
return $http.post("api/todo", reservation);
}
var EditReservation = function (id) {
return $http.put("api/todo/", + id);
}
var DeleteReservation = function (id) {
return $http.delete("api/todo/" + id);
}
var GetAll = function () {
return $http.get("api/todo");
}
return {
CreateReservation: CreateReservation,
EditReservation: EditReservation,
DeleteReservation: DeleteReservation,
GetAll: GetAll
}
}
this is a angular maincontroller code
app.controller('mainCtrl', mainCtrl);
function mainCtrl($scope, reservationService) {
$scope.list = [];
$scope.reservation = {};
getReservations();
InitDateTimePickers();
$scope.isSelected = function () {
return getSelectedItems().length > 0;
};
$scope.append = function (id) {
var editedItem = _.first(getSelectedItems());
$scope.reservation = editedItem;
reservationService.EditReservation(id).then(function (result) {
getReservations();
});
};
function getReservations() {
reservationService.GetAll().then(function (result) {
for (var i = 0; i < result.data.length; i++) {
result.data[i].timeFormatted = moment(result.data[i].Time, "HH:mm").format("hh:mm");
}
$scope.list = result.data;
});
}
function removeReservation(id) {
reservationService.DeleteReservation(id).then(function (result) {
getReservations();
});
}
$scope.add = function () {
reservationService.CreateReservation($scope.reservation).then(function (result) {
getReservations();
});
};
function InitDateTimePickers() {
$('#timepickerFrom').bootstrapMaterialDatePicker({ date: false, format: 'HH:mm' }).on('change', function (e, date) {
}); }
$scope.remain = function () {
var count = 0;
angular.forEach($scope.list, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
var getSelectedItems = function () {
return _.filter($scope.list, function (n) {
return n.done;
});
}
$scope.archive = function () {
var itemsToRemove = getSelectedItems();
_.each(itemsToRemove, function (item) {
removeReservation(item.id)
});
};
$scope.edit = function () {
var editedItem = _.first(getSelectedItems());
$scope.reservation = editedItem;
}
};
You can pass entire entity to the server to update it:
var EditReservation = function (reservation) {
return $http.put("api/todo/" + reservation.id, reservation);
}
Also it seems that this string contains typo: return $http.put("api/todo/", + id);

NIghtmare error in web scraping course details

Hi i am using nightmare for scrape data from website and also course details. I occur a issue :-
err: { message: 'navigation error',
code: 0,
details: 'OK',
url: 'https://www.myskills.gov.au/courses/details?Code=CHC14015' }
on each url traversal. Please suggest me to resolve this:
var Nightmare = require('nightmare')
var vo = require('vo')
var fs = require('fs')
var filesystem = require('file-system')
// var nightmare = Nightmare({show:true});
var sleep = require('sleep');
vo(run)(function(err, result) {
if (err) throw err
console.log("Hi");
})
function *run() {
var nightmare = Nightmare({show:true});
console.log("1st step *run");
yield nightmare
.goto('https://www.myskills.gov.au/courses/search/')
.wait(12000)
//.click('#select3 value="100")
.evaluate(function () {
var hrefs = [];
$('.search-result h4 a').each(function()
{
var course = new Object();
course.title = $(this).html();
course.link = $(this).attr('href');
course.code = $('.search-result .col-md-2.text-small
span').html();
hrefs.push(course);
});
return hrefs;
})
.then(function(str){
console.log("2nd step evaluate then on page load");
console.log(str);
for(var i=0; i< 8; i++)
{
console.log(i);
sleep.sleep(1);
var link = "https://www.myskills.gov.au";
var coursetitle = str[i].title
var courselink = link +str[i].link+"\n";
var coursesinglelink = link +str[i].link;
var courseData = coursetitle+"\n"+str[i].code+"\n"+courselink;
fs.appendFile('getcourselink.txt', courseData, function (err) {
if(err) console.log(err);
});
vo(run1)(function(err, result) {
if (err) console.log ("err: ",err);
console.log("Hi in run1");
//console.log(result);
});
function *run1() {
console.log("I 2nd time:-"+i);
console.log(coursesinglelink);
sleep.sleep(2);
var nightmare1 = Nightmare({show:true});
yield nightmare1
.goto(coursesinglelink)
.wait(9000)
.evaluate(function () {
var str="Hi";
var CourseDetails = $('#details #courseStructureDiv
#packagingrules').text();
str = str+"\n"+CourseDetails;
return str;
})
.then(function(str){
console.log("Run inner then",str);
fs.appendFile('getcourselink.txt', str, function (err) {
if(err) console.log(err);
});
// nightmare1.end();
});
}
//nightmare.end();
// nightmare.proc.disconnect();
// nightmare.proc.kill();
// nightmare.ended = true;
// nightmare = null;
}
});
}

Parse Cloud Code Error 141 success/error was not called

When the following code is executed, I get "Error: 141 success/error was not called", but I clearly return a success if a "round" is properly retrieved from a user's answer history.
Parse.Cloud.define("analyzeRound", function(request, response) {
var x = [];
var user = request.user;
user.get("answerHistory").get("round", {
success: function(educationRound) {
for (var i = 0; i < educationRound.length; i++) {
x.push(0);
}
response.success("success");
},
error: function(error) {
response.error("failed");
}
});
});
Any help would be much appreciated!
This ended up giving me what I was looking for, thanks Mo Nazemi!
Parse.Cloud.define("analyzeRound", function(request, response) {
var x = [];
var user = request.user;
var answerHistory = user.get("answerHistory");
answerHistory.fetch({
success: function(answerHistory) {
var round = answerHistory.get("round");
for (var i = 0; i < round.length; i++) {
x.push(0);
}
response.success("success");
},
error: function(error) {
response.error("failed");
}
});
});

meteor bindenvironnement issue

getTime: function () {
host="http://www.xxxxxx.com/";
res= Meteor.bindEnvironment(function(){
var Fiber = Meteor.require('fibers');
var Future = Meteor.require('fibers/future');
var future = new Future();
request(host, function (error, response, body) {
Fiber(function(){
if (!error && response.statusCode == 200) {
$ = cheerio.load(body);
var $thumbs = $('.thumb');
for (var i = 0, l = $thumbs.length ; i < l ; i++) {
// elements
var $thumb = $($thumbs[i]);
// save info
videourl=host+$thumb.find('a').attr('href');
videothumbs = [$thumb.find('img').attr('src')];
videos=Videos.insert({title:videoTitle,thumbs:videothumbs,lastUpdated:Date.now()});
}
return videos;
}
else {
return "error";
}
}).run()
});
}) ;
return res;
}
This is a server side method and returning undefined
Without bindenvironment it is returning error to use bindenvironemnt.
Am I using it properly, can somebody tell m the modifications in my code
You need a future to return the value of inner function:
Meteor.methods({
getTime: function() {
var future = new Future();
Meteor.bindEnvironment(function() {
future.return('Some value');
});
return future.wait();
},
});
Check out this Meteorpad for an example.
If you use suggestion from #saimeunt comment, then your code could be simplified into form:
SERVER:
Meteor.methods({
getSite:function(url){
var site = HTTP.get(url);
console.log("statusCode =\n " , site.statusCode);
console.log("content.length =\n ",site.content.length);
console.log("header =\n ",site.headers);
$ = cheerio.load(content);
...
}
})
CLIENT :
Meteor.call("getSite", "http://www.google.com");
See how it works

Setting $scope.items in Angular Binding

I have a service with the following function,
public object Get(AllUsers request)
{
var users = XYZ.GetAllUsers();
var userList = users.Cast<XYZ>();
return new AllUsers
{
UsersAcc = userList.Select(ConvertToEntity).ToList()
};
}
I am trying to get the results from angular controller.
function UserAccountController($scope, $location, $filter, UserAccount) {
#scope.items = function(){
var abc = UserAccount.query();
return abc.UsersAcc
}
}
Here is my Service
angular.module('userAccService', ['ngResource']).factory('UserAcc', function($resource) {
return $resource('/api/useracc/:id', {}, {
query: {
method: 'GET',
}
});
I am new to angular service, and can't seem to make it to work.
You need to create an array object and return it. After the query is done you can populate that same instance with the list UsersAcc. Keep in mind that $scope.items will be [] untill the query returns with data.
$scope.items = getUsersAcc();
function getUsersAcc() {
var dataArray = new Array();
UserAccount.query(function (data) {
var list = data.UsersAcc;
for (var i = 0, c = list.length; i < c; i++) {
dataArray.push(list[i]);
}
};
return dataArray;
};

Resources