Execute methods sequence - React - reactjs

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

Related

Need to use that counter variable outside since if i am calling that function am not getting output return

checkGridData(name: string, searchObj: ElementArrayFinder) {
if (name != "") {
let counter = 0;
let beforesplit = name;
let aftersplit = beforesplit.split("|");
var countval = searchObj.count();
return searchObj.count().then((count) => {
for (let i = 0; i < aftersplit.length; i++) {
let countval = searchObj.count();
// expect(count).toBe(expectedRecords[i]);
for (let j = 0; j < count; j++) {
searchObj.get(j).getText().then(function (text) {
if (text.indexOf(aftersplit[i]) !== -1) {
expect(text).toContain(aftersplit[i]);
++counter
//console.log("counter inside loop is" + counter)
}
return counter;
});
}
}
});
}
}
I am new to protractore. I wrote a function below
I am calling this in another function.
var abc = this.CheckGridData(ProductData.AddEquipment.EquipmentSelection, ProductObj.ele_equipmentvalidation)
console.log("Counter value returned:" + abc)
And i am getting this error
Counter value returned:ManagedPromise::5760 {[[PromiseStatus]]: "pending"}
I tried to do promise but I don't know how to do resolve promise. How to resolve inside for loop in the above, so that i can use it and know the concept? I tried various site but i couldn't understand how to resolve.
Because the function CheckGridData return a promise, so the variable abc is a promise.
To consume the eventual value of promise, you have to use then() as below:
checkGridData(name: string, searchObj: ElementArrayFinder) {
if (name != "") {
let counter = 0;
let beforesplit = name;
let aftersplit = beforesplit.split("|");
return searchObj.getText().then((texts) => {
// texts is an string array of text of all elements of searchObj
for (let i = 0; i < aftersplit.length; i++) {
if(texts.includes(aftersplit[i])) {
++counter;
}
}
return counter;
};
}
}
var abc = this.CheckGridData(ProductData.AddEquipment.EquipmentSelection,
ProductObj.ele_equipmentvalidation)
abc.then(function(count){
console.log(count);
})

I cant break my foreach with ajax inside

I have this:
var addresses_tmp = addresses.slice();
var final_addresses = [];
addresses.forEach(function (current_address, i) {
var near_addresses = [];
near_addresses.push(current_address);
addresses_tmp.forEach(function (next_address, j) {
if (current_address.address.info.code != next_address.address.info.code) {
var data = {
key : $scope.MicrosoftKey,
optmz : "distance",
routeAttributes : "routePath"
}
data["wp.0"] = current_address.address.location.lat + "," + current_address.address.location.lng;
data["wp.1"] = next_address.address.location.lat + "," + next_address.address.location.lng;
ajax.sendApiRequest(data, "GET", "http://dev.virtualearth.net/REST/V1/Routes/Driving", is_url=true).then(
function(response) {
var distance = response.data.resourceSets[0].resources[0].travelDistance;
if (distance < 0.020) {
near_addresses.push(next_address);
addresses_tmp.splice(j, 1);
}
if (j == addresses.length - 1) {
final_addresses.push(near_addresses);
if (near_addresses.length == 1) {
addresses_tmp.splice(j, 1);
}
addresses_tmp.splice(i, 1);
}
// if (count == addresses.length * addresses.length) {
// console.log("ya he acabado todasssss")
// }
},
function(error) {
console.log("error", error);
}
)
}
})
})
And I would like to break all function when the first foreach and the second foreach are finished but I cant put if condition to do this.
As I have ajax inside the second foreach, my variables are crazy so I cant put an if condition to break it.
I need to do this because I am compare two arrays and getting distance between two points (one in the first array and second in the other array)

Using Lodash _.map and Typescript to create new column for filtering

In my controller I have code that filters just fine but i want to create a new field that concatenates two fields for an Angular filter in html. This is what I have that doesn't work.. Is this possible?
private filterByColumns: string = "";
getData = (): void => {
var vm = this;
this.carHopService.getDetails({ id: this.$state.params["id"], type: this.$state.params["type"] }).then(
(data: any) => {
vm.primaryCarHopData = _.filter(data.carHopList, {
carHopType: "Primary"
});
---> **vm.primaryCarHopData = _.map(data.carHopList, {
vm.filterByColumns=fullName + " " + age
});**
});
};
That's not how map works. In the callback function, you need to return something:
_.map([0,1,2], (x) => x + 1)
> [1,2,3]
// old syntax
_.map([0,1,2], function (x) { return x + 1 })
> [1,2,3]
You can simply replace _.map with _.forEach and you will have your mapped data in data.carHopList.
Clarification:
I'm not good with words so let me put here very simple implementations for both forEach and map:
// these functions do not mock lodash counterparts 100%
// as lodash fns can work with objects too
// and they have some shortcuts, see docs
function forEach(arr, callback) {
for(var i = 0; i < arr.length; i++) {
callback(arr[i], i);
}
return arr;
}
function map(arr, callback) {
var newArr = [];
for(var i = 0; i < arr.length; i++) {
newArr[i] = callback(arr[i], i);
}
return newArr;
}
Someone had steered me in the direction of map. What I ended up doing was using Angular by adding this to controller:
filterTextByCols = (row) => {
return (angular.lowercase(row.fullName).indexOf(angular.lowercase(this.filterQuery) || '') !== -1 ||
angular.lowercase(row.birthDate).indexOf(angular.lowercase(this.filterQuery) || '') !== -1);
}
And then using filterTextByCols in filter:
<div ng-repeat="person in vm.persons | orderBy:sortType:sortReverse | filter: vm.filterTextByCols">

AngularJS ng-repeat view not updating after data update

have a some data one my page that is in a ng-repeat.
When the page and data 1st loads the data shows up.
When I move away from the page (using Angular Routing) make a change to the data (gets saved in db) then come back into the page (make call to db get new data) the ng-repeat data does not refresh. I can see the new data loading into the array and it is the new data.
I start the process on the page with
var sp = this;
sp.viewData = [];
sp.employee = [];
sp.ViewDataTwo = [];
$(document).ready(function () {
var testHeader = setInterval(function () { myTimer() }, 1000);
function myTimer() {
if (addHeaderToken() != undefined) {
clearInterval(testHeader);
sp.usageText = "";
if (sessionStorage.getItem(tokenKey) != null) {
sp.associatedInfo = JSON.parse(getassociatedInfo());
loadDataOne();
loadDataTwo();
}
}
}
});
I do this because I need to get my security toke from a JS script that I have no power over changes. So I need to make sure the code has ran to get me the token.
here are the functions I call..
function loadPasses() {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
$http.get('/api/Employee/xxx', { params: { employeeId: sp.employeeId } }).then(function (data) {
sp.viewData = data.data;
for (var i = 0; i < $scope. viewData.length; i++) {
sp.passes[i].sortDateDisplay = (data.data.status == "Active" ? data.data.DateStart + "-" + data.data[i].DateEnd : data.data[i].visitDate);
sp.passes[i].sortDate = (data.data[i].status == "Active" ? data.data[i].DateStart: data.data[i].visitDate);
}
});
}
function loadDataTwo () {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
if (sessionStorage.getItem(tokenKey) != null) $http.get('/api/Employee',
{
params: { employeeId: sp.employeeId }
}).then(function (data) {
sp.employee = data.data;
var tempPassString = "";
sp.ViewDataTwo = [];
var totalA = 0;
var totalU = 0;
for (var p = 0; p < sp.employee.dataX.length; p++) {
sp.ViewDataTwo.push(sp.employee.dataX[p].description + "(" + /** math to update description **// + ")");
totalA += parseInt(parseInt(sp.employee.dataX[p].Anumber));
totalU += parseInt(sp.employee.dataX[p].Bnumber));
}
sp.usageArr.push(" Total: " + totalA- totalU) + "/" + totalA + " Available");
//$scope.$apply();
});
}
One my view sp.viewData and sp.ViewDataTwo are both in ng-repeats.
Works well on load.. when I go out and come back in. I see the data reloading. But the view does not.
I have hacked the Dom to get it to work for now. But I would like to do it the right way..
Any help.
I have used
$scope.$apply();
But it tells me the digest is already in process;
the views are in a template..
Please help

Name database child in Firebase?

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.

Resources