Hi I have this code for the purpose of checking if there are users in the database, if it finds shows a list of users on a view, otherwise shows a view with form of user creation, but didn't work the check expression what I'm doing wrong
users = Users.query();
users.$promise.then(
function (data) {
if (!data) {
$location.url('/NewUser')
} else {
$location.url('/UsersList')
}
});
It is probably returning an empty array in case nothing is found. Try checking the data length.
if (data.length == 0) {
$location.url('/NewUser')
} else {
$location.url('/UsersList')
}
Related
I made a loop to check whether a key doesn't exsist in another object. As soon as this condition is true it should stop and redirect to a certain URL. I got the loop working but my issue is that as soon as the condition is met. It still continues to loop for the remaining items. Meaning it will never stop and creates some kind of infite loop. How can i make sure that if the condition (if) is met. the loop stops.
requiredResource:
resources: (first time it is empty)
Loop:
// For every requiredResource check if it exist in the resources. (right now it is one)
requiredResource.forEach((item: any) => {
// Check if there are resources, if not go get them
if(resources.length !== 0){
// Resources are filled with 2 examples
Object.keys(resources).forEach(value => {
//if the required is not in there, go get this resource and stop the loop
if(value !== item.name){
// Go get the specific resource that is missing
window.location.assign(`getspecificresource.com`);
} else {
// Key from resource is matching the required key. you can continue
//continue
}
});
} else {
// get resources
window.location.assign(`getalistwithresources.com`);
}
});
You can use some() array method for this like:
const found = requiredResource.some(({name}) => Object.keys(resources).indexOf(name) > -1)
if (!found) {
window.location.assign(`getspecificresource.com`);
} else {
// Key from resource is matching the required key. you can continue
//continue
}
EDIT:
Based on the discussion, you can updated your code like this to achieve the required behaviour as we can't break from a forEach loop:
requiredResource.some((item) => {
// Check if there are resources, if not go get them
if (resources.length !== 0) {
// Resources are filled with 2 examples
Object.keys(resources).some(value => {
//if the required is not in there, go get this resource and stop the loop
if (value !== item.name) {
// Go get the specific resource that is missing
window.location.assign(`getspecificresource.com`);
return true;
} else {
// Key from resource is matching the required key. you can continue
//continue
return false;
}
});
return false;
} else {
// get resources
window.location.assign(`getalistwithresources.com`);
return true;
}
});
Just using the some() with return true to break out of the loop here.
You could try something like this...
let obj = {
'a': 1,
'b': 2,
'c': 3
}
console.log(obj.a)
Object.keys(obj).some(x=>{
console.log(obj[x])
return obj[x]==2
})
And use the return statement to break the loop, does that help?
I'm doing filtering on a data displayed in a view which is working correctly. I've placed a filter bar at the top of the screen where a user can filter the records. What I want to achieve is when the variable the user enters is not found in the records a function should be called
filterProducts(ev) {
this.productService.list = this.reOrderList;
const val = ev.target.value;
if (val && val.trim() !== '') {
this.productService.list = this.reOrderList.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
} else {
// value doesn't exist console.log('call another function')
}
}
Check if any items are left in the array after the filter is complete:
if (this.productService.list.length) {
// The user's query was found in the array
} else {
// The user's query was not found in the array
}
I am trying to display "No Results Found" in the case where someone uses my search feature to search for something that returns no results from the database. The problem I'm running into is that "No Results Found" prints to the screen right away - then disappear when a search query is actually being evaluated - and then reappears if no results were found. In other words, it's working as it should EXCEPT that it should wait till a query is actually triggered and evaluated before printing "No Results Found" to the screen. Conceptually what's the best way to do this? On the one hand it occurs to me that I could just use a timeout. But that's not really solving the problem directly. So what would be the best way to approach this? This is the code I have for the function:
public get noResultsFound(): boolean
{
if (this.query && !this._isSearching && !this.hasResults) {
return true;
}
}
Here's my view code:
<div *ngIf="inputHasFocus && noResultsFound" class="no-results-found">No Results Found</div>
Promises sound like what you need :D
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Something along the lines of this.
search = (paramObj) : Promise<SomeDataClass> => {
// Some search logic
}
requestSearch() {
this.search(null).then((result) => {
if (result.length === 0)
{
//logic for showing 0 results here
}
else{
// Show result?
}
})
}
A more complete example would look a bit like this.
class example {
public someBool = false;
public search = (paramObj): Promise<Array<string>> => {
this.someBool = !this.someBool;
return new Promise<Array<string>>((resolver) => {
// This just simulates something taking time.
setTimeout(() => {
if (this.someBool) {
resolver([]);
} else {
resolver(["hi","there"]);
}
}, 1000)
});
}
public requestSearch() {
this.search(null).then((result) => {
if (result.length === 0) {
console.log("empty")
}
else {
console.log(result)
}
})
}
}
So, in the end I was able to resolve this not by using some kind of debounce timeout, but by changing what the function was paying attention to - so to speak. By handling it this way the "No Results Found" never triggers before it's supposed to. This is what I ended up using:
public get noResultsFound(): boolean
{
if (!Object.isNullOrUndefined(this._results) && this._results.length < 1) {
return true;
}
}
In my angularjs app, i need to manually remove or add old/new data from a data array (service is executed in a loop). For remove, i use slice(); but there is a problem: the item is correctly removed but execVerif_distant(); is not executed for the next item. With my actual code, execVerif_distant(); is executed for each item only half a time. For example, if i need to remove entire array, only half is removed.
// start the loop, search in local datas
angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
execVerif_local(itemLocalCages.url);
});
function execVerif_local(identifiant) {
var iterSearch_local = 0;
angular.forEach(responseZS, function(itemDistantCages) {
if (itemDistantCages.url == identifiant) {
iterSearch_local++;
}
});
// if we not find the local datas in distant datas
if (iterSearch_local == 0) {
// verifItem(); call
verifItem('remove', identifiant);
}
}
// verifItem();
function verifItem(action, url) {
if (action == 'remove') {
var iIndex = -1;
angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
iIndex++;
if (itemLocalCages.url == url) {
$scope.seaDocument.datas.cages.splice(iIndex,1);
}
});
} else {
// do nothing
}
}
what's wrong ?
The problem is that the foreach is iterating over the same object you are removing things from. To avoid this behavior clone the object you are iterating before the loop and work with them as separate:
// ... code
var arrCopy = $scope.seaDocument.datas.cages.slice(); //this will create a deep copy.
angular.forEach(arrCopy, function(itemLocalCages) {
iIndex++;
if (itemLocalCages.url == url) {
$scope.seaDocument.datas.cages.splice(iIndex,1);
}
});
//... more code
I had a read of the meme example but it doesn't seem to update, just create new objects! What I want is to
a. find some given db table
b. update some fields in the db table
c. save the db table back to the database
Given this code, what is the missing piece so that I can actually update an object?
query.find(
function(results){
if (results.length > 0){
return results[0];
} else {
//no object found, so i want to make an object... do i do that here?
return null;
}
},
function(error){
response.error("ServerDown");
console.error("ServerDown - getModuleIfAny URGENT. Failed to retrieve from the ModuleResults table" + +error.code+ " " +error.message);
}
).then(
function(obj){
var module;
if (obj != null){
console.log("old");
module = obj;
module.moduleId = 10; //let's just say this is where i update the field
//is this how i'd update some column in the database?
} else {
console.log("new");
var theModuleClass = Parse.Object.extend("ModuleResults");
module= new theModuleClass();
}
module.save().then(
function(){
response.success("YAY");
},
function(error) {
response.error('Failed saving: '+error.code);
}
);
},
function(error){
console.log("sod");
}
);
I thought the above code would work - but it does not. When it finds an object, it instead refuses to save, stupidly telling me that my object has no "save" method.
First I would double check the version of the javascript sdk you're using in your cloud code. Make sure it's up to date e.g. 1.2.8. The version is set in the config/global.json file under your cloud code directory.
Assuming you're up to date I would try modifying your code by chaining the promises using multiple then's like so:
query.find().then(function(results){
if (results.length > 0){
return results[0];
} else {
//no object found, so i want to make an object... do i do that here?
return null;
}
},
function(error){
response.error("ServerDown");
console.error("ServerDown - getModuleIfAny URGENT. Failed to retrieve from the ModuleResults table" + +error.code+ " " +error.message);
}).then(function(obj){
var module;
if (obj != null){
console.log("old");
module = obj;
module.moduleId = 10; //let's just say this is where i update the field
//is this how i'd update some column in the database?
} else {
console.log("new");
var theModuleClass = Parse.Object.extend("ModuleResults");
module= new theModuleClass();
}
module.save();
}).then(function(result) {
// the object was saved.
},
function(error) {
// there was some error.
});
I think this should work. Fingers crossed. Cheers!