Name database child in Firebase? - database

This is the code I have.
function saveTrip()
{
routeData.clear();
for (var i = 0; i < dirDisplay.directions.routes[0].legs.length; i++) {
for (var j = 0; j < dirDisplay.directions.routes[0].legs[i].steps.length; j++) {
routeData.push(dirDisplay.directions.routes[0].legs[i].steps[j].path);
}
}
routeLinesRef.push(routeData, function(error){
if (error) {
$('#savedSpan').html('Data could not be saved.' + error);
} else {
$('#savedSpan').html('Data saved successfully!');
}
});
}
Array.prototype.clear = function() {
this.splice(0, this.length);
};
routeLinesRef.limit(10).on('child_added', function(snapshot)
{
// loop over each route we get from firebase
route = snapshot.val();
What function should be written to write into the hierarchy as shown in the image?
id = snapshot.name();
// make an array that is initially blank
// It will contain all the latitude and longitudes of each point on in the route
var routeCoordinates = [];
// This loops over each point on the route
for (var i=0; i<route.length; i++)
{
for (var j in route[i])
{
if (j==0 && i>0)
{
continue
}
else
{
This part just takes each point on the route, and converts it into
a google maps LatLng object. For example, if the data is [58.23, 18.8], it will do:
new google.maps.LatLng(58.23, 18.8) to it, which turns it into a format that google maps likes.
if (route[i][j].lb && route[i][j].mb) {
routeCoordinates.push(new google.maps.LatLng
(route[i][j].lb, route[i][j].mb));
//console.log(j + ' ' + snapshot.val()[route][i][j].lb, snapshot.val()[route][i][j].mb);
}
}
}
}
What should I do? I can't find any tutorial or anything.

Related

Execute methods sequence - React

I have written following code to get current user group Ids and later from that Ids I wanted to filter data from SharePoint list. First I want to execute
ServiceManager.getRemoteService().getCurrentUserGroups()
method. Once I get group Ids, I want to execute the next method. But unfortunately filter part of the REST query is blank because
this.groupIdString
is blank. This may be because both methods are executed same time. I'm new to React and I want to know is there any best approach to manage this scenario. Basically I want to execute the methods in the order I write.
public componentDidMount() {
this.groupIdString= "";
ServiceManager.getRemoteService().getCurrentUserGroups(this.props.siteUrl, "/_api/web/currentuser/groups").then((value) => {
if (value[0]) {
for (let i: number = 0; i < value.length; i++) {
if(value[i].Id != undefined){
this.groupIdString += "(UserGroupsId eq " + value[i].Id.toString()+")";
}
}
}
});
const restQuery = "/_api/Web/Lists/GetByTitle('Weather')/Items?$select=Title,NewsBody,UserGroupsId&$filter=("+this.groupIdString+")";
ServiceManager.getRemoteService().getWeatherListItems(this.props.siteUrl, restQuery).then((value) => {
if (value[0]) {
//code
}
});
}
#Sivakumar Piratheeban,
You can put the second request in the callback of the first call.
public componentDidMount() {
this.groupIdString = "";
ServiceManager.getRemoteService().getCurrentUserGroups(this.props.siteUrl, "/_api/web/currentuser/groups").then((value) => {
if (value[0]) {
for (let i: number = 0; i < value.length; i++) {
if (value[i].Id != undefined) {
this.groupIdString += "(UserGroupsId eq " + value[i].Id.toString() + ")";
}
}
// Second
const restQuery = "/_api/Web/Lists/GetByTitle('Weather')/Items?$select=Title,NewsBody,UserGroupsId&$filter=(" + this.groupIdString + ")";
ServiceManager.getRemoteService().getWeatherListItems(this.props.siteUrl, restQuery).then((value) => {
if (value[0]) {
//code
}
});
//
}
});
}
BR

How to set factory properties so they are independent from one another?

Consider the below Angularjs 'service'. I would like to keep all my 'entries' related variables in this service so I can use them across controllers - as I believe the ideal angular pattern calls for. However, if I manipulate anyone of the variables from a controller - entries, entries_Sorted, entries_Loaded within the service object - they all seem to take on the same new value. I understand the factory object is a singleton but shouldn't these variables be independent? I don't expect or understand the behavior I am seeing. How is this useful? I must be doing something wrong.
To be clear:
If I set local variables within my controllers using this service's return methods, then update those local variables, all the three entries variables within the service will take on the new values.
Service code:
angular.
module('core.entry').
factory('Entry', ['$http', 'Topten', 'Stack', 'User',
function($http, Topten, Stack, User) {
var entries = [];
var entries_Sorted = [];
var entries_Loaded = [];
var service = {};
service.getEntries = function(stackId, callback) {
return $http.get('stacks/' + stackId + '/entries/')
.success(function(data) {
entries = data["entries"];
Topten.setToptens(data["topTen"]);
Stack.setOpenStack(data["stack"]);
callback(null, data);
})
.error(function(err) {
callback(err, null);
});
};
service.returnEntries = function() {
return entries;
}
service.sortEntries = function(callback) {
// 1. Loop through entries inner looping on toptens - adding topten score to total score
for (var i = 0; i < entries.length; i++) {
var thisEntry = entries[i];
var totalScore = 0;
var toptens = Topten.returnToptens();
for (var j = 0; j < toptens.length; j++) {
var thisTopten = toptens[j];
if (thisTopten["entryId"]) {
if (thisEntry["_id"] == thisTopten["entryId"]._id) {
totalScore = totalScore + thisTopten["score"];
}
}
}
thisEntry.totalScore = totalScore;
// 2. Add net (likes - dislikes) to entry.totalScore
for (var j = 0; j < thisEntry.votes.length; j++) {
var thisVote = thisEntry.votes[j]["vote"];
if (thisVote == "up") {
thisEntry["up"] = thisEntry["up"] + 1;
} else if (thisVote == "down") {
thisEntry["down"] = thisEntry["down"] + 1;
}
}
var netLikes = thisEntry["up"] - thisEntry["down"]; // one point each
thisEntry["totalScore"] = thisEntry["totalScore"] + netLikes;
}
// 3. Sort entries by entry.totalScore and return
entries_Sorted = entries.sort(function(a, b) {
return b.totalScore - a.totalScore;
});
callback();
};
service.returnEntries_Sorted = function() {
return entries_Sorted;
};
return service;
}
]);
My controller's code:
Entry.getEntries($routeParams.stackId, function(err, data) {
if(err) {
}
// get sorted entries (after return from getEntries)
Entry.sortEntries(function() {
self.entries_Sorted = Entry.returnEntries_Sorted();
self.loadMore();
});
});
self.loadMore = function() {
self.entries_Loaded = self.entries_Loaded.concat(self.entries_Sorted.splice(page * increment, increment));
self.page +=1;
}
Problem: After I call this local 'load_More' function, the properties in my service - entries, _Sorted, _Loaded - will all have the new 'spliced' value. ie. Entry.entries will have the same value as the controller's local self.entries_Sorted.

iterating inside a $http.get

I've this block of code which displays 20 items per request.
.controller('ActorController',function($scope,$http) {
$scope.getActors = function () {
var actors = $http.get(https://api.themoviedb.org/3/person/popular&page=1);
actors.then(
function (response) {
$scope.actors = response.data.results;
}
);
}
})
Instead of page=1, if i put page=2, I'll get another set of 20 items and so on. How to iterate inside the $http.get if I want more than 1 get request in a single page? I want to display the 2nd 20 items after displaying the 1st 20.
So you're saying that you want to make multiple calls to $http.get in a loop? If so you'd do something like this:
.controller('ActorController',function($scope,$http) {
$scope.getActors = function () {
for(var i = 0; i < 5; i++) {
getPage(i);
}
}
function getPage(i) {
var actors = $http.get('https://api.themoviedb.org/3/person/popular&page=' + i);
actors.then(function (response) {
for(var j = 0; j < response.data.results.length; j++) {
$scope.actors.push(response.data.results[j]);
}
});
}
})
That will put the data for the first 5 pages into the $scope.actors array.
you can use $q.all to send multiple http requests at once
var fulAr = [];
for (var i = 1; i <= 2; i++) {
fulAr.push($http.get("https://api.themoviedb.org/3/person/popular&page=" + i))
}
$q.all(fulAr).then(function(response) {
console.log(response[0].data) //page 1 content
console.log(response[1].data) //page 2 content
for(var j = 0; j < response.length; j++) {
$scope.actors = $scope.actors.concat(response[j].data.results);
}
})
Make sure to inject $q to controller

Why array save last data and doesn't clears?

I have a simple AngularJs application of medical cards.
I have storage with it and display it at my home.html using dx-datagrid:
One card has many records, I get records of card from recordsArray by cardId
getVardsRecordsByCardId: function (id, recordsArray) {
if (recordsArray.length != 0) {
for (var i = 0; i < recordsArray.length; i++) {
if (recordsArray[i].cardId === id) {
cardsRecords = cardsRecords.concat(recordsArray[i]);
}
}
}
return cardsRecords;
}
Now I have records just in the third card. I added a function on button for testing it:
var jdskla = [];
var localCardId = 0;
$scope.showCardDetails = {
text: "",
type: "default",
icon: "preferences",
onClick: function () {
if ($scope.itemIdFromShowButton) {
$location.path('/carddetail/' + $scope.itemIdFromShowButton);
var jdskla =[];
var jdskla = businessLogicOfMyApp.getVardsRecordsByCardId($scope.itemIdFromShowButton, $scope.recordsArray);
console.log($scope.itemIdFromShowButton)
console.log(jdskla);
}
else {
alert("Error!!!");
}
}
};
1,3,1 is cardId's and array of records. But, why array of card records don't clears and save last data?
May be somebody know how I can resolve it? Thanks for your answers!
P.S. I'm using ng-view directive in my app and i tried to clear my array use another button:
$scope.backToGeneralPage = {
text: "Back",
onClick: function () {
jdskla = [];
$location.path('/');
}
};
but it wasn't helpful.
You should initialize cardsRecords array in function getVardsRecordsByCardId.
getVardsRecordsByCardId: function (id, recordsArray) {
var cardsRecords = []; // initialize array locally
if (recordsArray.length != 0) {
for (var i = 0; i < recordsArray.length; i++) {
if (recordsArray[i].cardId === id) {
cardsRecords.push(recordsArray[i]);
}
}
}
return cardsRecords;
}

Two for loops in one function will not save an array after exiting for loop

I have two arrays I need to compare in a test. I am testing a filter, it reads in an array of numbers and saves to spareArray. I then click on a filter button which is also the element the int list is listed in, style. I read in the list again and save it to the second array, spareIntArray. After the readin I send the arrays to two methods, one parses string to float and the second gets ride of '-' that are in my lists I do not want to compare. However after the run of the second for loop reading in spareIntArray the array is set to undefined. I tested that the array is filled with elements by doing a log and it seems to be. I am quite confused what is happening here.
/**
* Created by nphillips on 8/11/2015.
*/
var helper = require('./../pages/helper-page.js');
var capacityPage = module.exports = {
variables: {
//the theaterStyle element list
theaterStyle: element.all(by.css("[data-style='theater']")),
},
readsInTheater: function() {
capacityPage.readsIn(capacityPage.variables.theaterStyle);
},
removesDashes: function(style, array) {
while (array.indexOf('-') !== -1) {
array.splice(array.indexOf('-'), 1);
};
console.log(array + "count ");
return array;
},
readsIn: function(style) {
var spareArray = [];
var spareIntArray = [];
style.count().then(function(count) {
console.log(count);
j = 0;
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
style.get(i).getText().then(function(text) {
spareArray[j] = text;
console.log(text, spareArray[j], j);
expect(text).toEqual(spareArray[j++]);
});
}
}).then(function() {
// style.click()
browser.executeScript("arguments[0].scrollIntoView();", style.get(0).getWebElement());
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
style.get(i).getText().then(function(text) {
spareIntArray[j] = text;
console.log(text, spareIntArray[j], j + "frawer");
expect(text).toEqual(spareIntArray[j++]);
});
};
});
spareArray = capacityPage.stringToFloatArray(spareArray);
spareIntArray = capacityPage.stringToFloatArray(spareIntArray);
capacityPage.removesDashes(style, spareArray);
capacityPage.removesDashes(style, spareIntArray);
expect(spareArray).toEqual(spareIntArray);
});
},
stringToFloatArray: function(array) {
function int_arr(a, b) {
return parseFloat(a) - parseFloat(b);
}
array = array.sort(int_arr);
console.log(array + "float");
return array;
},
};
Is spareIntArray being undefined?. It could be because you are calling stringToFloatArray on spareIntArray before it is filled. I think that your check should be inside the promise callback. However I am a bit concerned on why you are using asynchronous data retrieval on the document. Is there a way to do it in a synchronous way? Soemething like
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
var text = style.get(i).getText();
spareArray.push(text);
console.log(text, spareArray[i], i);
expect(text).toEqual(spareArray[i]);
});
}
}).then(function() {
// style.click()
browser.executeScript("arguments[0].scrollIntoView();", style.get(0).getWebElement());
style.count().then(function(count) {
console.log(count);
for (var i = 0; i < count; i++) {
//scrolls down the list element by element
browser.executeScript("arguments[0].scrollIntoView();", style.get(i).getWebElement());
var text = style.get(i);
spareIntArray.push(text);
console.log(text, spareIntArray[i], i + "frawer");
expect(text).toEqual(spareIntArray[i]);
};
spareArray = capacityPage.stringToFloatArray(spareArray);
spareIntArray = capacityPage.stringToFloatArray(spareIntArray);
capacityPage.removesDashes(style, spareArray);
capacityPage.removesDashes(style, spareIntArray);
expect(spareArray).toEqual(spareIntArray);
});
});
},

Resources