dataSource.filter filters ID which is not visible in frontend - angularjs

Basically, this is my code
applySearchFilter(filterValue: string) {
this.values = filterValue.toString().toLowerCase();
this.dataSource.filter = this.values;
}
with "this.dataSource.filter" I can filter any data out of it, but I want to add an exception to keyId.... See the object below.
my object looks something like this.
{
keyId: "00000000-0000-0000-0000-000000010001",
name: "Test 10",
location: "New York"
}
When I input "10", it filters everything in the dataSource that has a 10. So, not only the name has "10" in it, but the keyId too. I took an hour to realize what this kept happening... and it is because of keyId xD
Allthough I get the whole object with keyId included, keyId is not shown in frontend and should not be search/filter-able. Even if it does not show keyId in frontend, he searches for the object that has that keyid
I am not sure how to fix it right now, since something like this.dataSource.data.name or so does not work...
I'd appreciate if you gals and girls would give me some tips.
Oh and here is where I get my data to that get filtered.
public getObject(): void {
this.service.getObjectMethod().then(data=> {
this.dataSource.data = data;
}, (err: Error) => { console.log(err.message); });
}

i solved this issue using.
public filterData(): void {
if (this.inputValues.trim().length !== 0) {
this.filteredValues = [];
this.dataSource.data.filter(data => {
if (data.name.toLowerCase().includes((this.inputValues).toLowerCase()) ||
data.opensCategory.toLowerCase().includes((this.inputValues).toLowerCase())) {
return true && this.filteredValues.push(data);
}
});
this.dataSource.data = this.filteredValues;
}
}

Use the following code to search.
applySearchFilter(filterValue: string) {
this.dataSource.filterPredicate = function (data: any, filterValue: string) {
return data.name.trim().toLocaleLowerCase().indexOf(filterValue.trim().toLocaleLowerCase()) >= 0;
};
}

Related

How can I remove an Object from a MongoDB array without $pull?

I'm trying to make a social media app, so I wrote a route that allows users to like posts, but If someone already liked it and pressed "like" again - It should remove the like, right? The point is - I can't use $pull since it uses findByIdAndUpdate, which can only be used if likes have their own separated model, but I don't have it because I think that overworks db a bit.
I use for to cycle trough an array and scan an Id of an Object and validate if it matches an Id of the logged user
const post = await Post.findById(request.params.post_id)
for (let i = 0; i < post.likes.length; i++) {
if (post.likes[i].userId === request.user.id) {
// Remove post.likes.[i] from the database completely
}
}
Here is how post looks like in Mongo documents:
{ "userId": "627eae4ed5b20f818d7a8142", "title": "Simple Post Title", "body": "Whatever",
"likes": [{ "userId": "627eae4ed5b20f818d7a8142", "likedAt": "14:58:20" }], }
If there is something else I need to provide - don't hesitate to ask.
Nevermind guys! I did it, I only needed to update the Post collection, nothing more!
for (let i = 0; i < post.likes.length; i++) {
if (post.likes[i].userId === request.user.id) {
Post
.findByIdAndUpdate(post._id, {
$pull: { likes: post.likes[i] }
}, {
new: true,
runValidators: true
})
.then((updated_post) => {
response.status(200).json({ success: true, updated_post: updated_post })
})
.catch(() => {
return next(
new ErrorResponse(`An error occurred while updating the post`, 400)
)
})
}
}
It does gives me an error, but I think I'll manage
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

ANGULAR Components array key in result get value by id

this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.

query string params as array of objects - issues javascript

I've got a problem!
I need to get in query string params encode something like this:
filters[0].columnName: createdBy
filters[0].value: ew
filters[0].operation: contains
filters[1].columnName: title
filters[1].value: eweqw
filters[1].operation: endsWith
but I just get nothing but...
filters: [name,"contains", o'}]
my code is:
const getQueryStringFilters = (): string => {
let filter = filters
.reduce((acc, { columnName, value }) => {
acc.push(encodeURIComponent(`[${columnName},"contains", ${value}'}]`));
return acc;
}, [])
.join(',"and",');
if (filters.length > 1) {
filter = `[${filter}]`;
}
return filter;
};
and I am using devexpress react-grid :( cannot find solution... somebody could help me out?

Is there a protractor.promise.when() method?

I see that I can use protractor.promise.all(). Is there a protractor.promise.when()? And where can I find out more about it and how to use it?
My problem is I need to resolve all getText() promises, determine which ones fail and provide blanks for those that failed.
For example:
function getValues() {
let pFirstName = $('#firstname').getText();
let pLastName = $('#lastname').getText();
let pSSN = $('#ssn').getText();
return protractor.promise.when([pFirstName, pLastName, pSSN])
.then(function(values) {
return {
"first": values[0],
"last": values[1],
"ssn": values[2] // This value may or may not be on the DOM, how do I check it and provide an alternate value?
};
});
}
UPDATE:
As I'm continuing my research, I see this is more of a webdriver issue. And, perhaps I need to pull in Bluebird. I'm not sure.
To answer the question below, "what do you mean by which ones fail?"
Suppose that the $('#ssn') ElementFinder doesn't actually find an element that matches #ssn. The getText() method would reject on the promise and deliver an element not found error. And, so, I would the following two situations:
<span id="firstname">Joe</span>
<span id="lastname">Smith</span>
<span id="ssn">123-45-6789</span>
getValues().then(res => console.log(res));
would return {"first": "Joe","last":"Smith","ssn":"123-45-6789"}
In the following situation, where a user is not supposed to see the SSN, and angular doesn't even create the element, we may have:
<span id="firstname">Joe</span>
<span id="lastname">Smith</span>
getValues().then(res => console.log());
I would expect that the return should be: {"first":"Joe","last":"Smith"} or {"first":"Joe","last":"Smith","ssn":""}
Here is an another idea - a more generic one - get all the related span elements and use reduce() to return an object with input ids and texts:
var inputs = $$("span[id]"); // TODO: make the locator more specific
var values = inputs.reduce(function (obj, input) {
return input.getAttribute("id").then(function (fieldName) {
return input.getText().then(function (fieldValue) {
obj[fieldName] = fieldValue;
});
});
}, {});
You can also change {} to, say, {"firstname": "", "lastname": "", "ssn": ""} to have the default values for fields that don't exist.
Unless a better answer comes along, I think this may be the answer (just catch the reject during the getText() call).
function getValues() {
let pFirstName = $('#firstname').getText().catch(() => "");
let pLastName = $('#lastname').getText().catch(() => "");
let pSSN = $('#ssn').getText().catch(() => "");
return protractor.promise.when([pFirstName, pLastName, pSSN])
.then(function(values) {
return {
"first": values[0],
"last": values[1],
"ssn": values[2]
};
});
}
At least, it works when I do something similar in JSFiddle:
function iffy(rVal, cond) {
return new Promise(function(resolve, reject) {
if (cond) {
resolve(rVal);
} else {
reject(new Error("This is in error"));
}
});
}
let pTruthy = iffy("true", true)
.catch(() => "Caught the error");
let pFalsy = iffy("false", false)
.catch(() => "Caught the error");
Promise.all([pTruthy, pFalsy])
.then(values => console.log(values))
.catch(err => console.log(err));
iffy("false", false)
.then(val => console.log(val))
.catch(err => console.log(err.toString()));
Not the very generic approach, but you can check if the SSN field is present explicitly. Something along these lines:
function getValues() {
let pFirstName = $('#firstname').getText();
let pLastName = $('#lastname').getText();
let isSSNPresent = $('#ssn').isPresent();
return protractor.promise.all([pFirstName, pLastName, isSSNPresent]).then(function(values) {
let result = {
"first": values[0],
"last": values[1]
};
if (values[2]) {
$('#ssn').getText().then(function (ssn) {
result.ssn = ssn
});
}
return result;
});
}
(not tested)

Best way to check if a value is in a multiselectlist?

Sorry if this is a silly question.
But I've been struggling with this for a while. I want to check if a MultiSelectlist I have contains a particular value. What is the best way to do this? I tried using the contains() function, but it doesn't like it.
Thank you in advance for your help
Apologies for not having done this earlier. New to SO, what can I say!
I wrote the following script to get the values in the MultiSelectList into an array and post it to an action method using Ajax. I then used the Array.Exists() method in the View to check if the string is in the array or not.
var selValuesArr = [];
$("#selColList option").each(function (i, current) {
selValuesArr[i] = $(current).val();
});
Ajax call:
$.ajax({
url: "/Main/Index",
data: { "selValues": selValuesArr }, //JSON.stringify(selValues) },
type: "POST",
success: function (data) {
$("#Grid").html(data);
}
});
And in my View, I have the following function (it takes an int, rather than a string)
#functions {
public bool findColumn(int colId, String[] strArr)
{
String temp = colId.ToString() ;
if (Array.Exists(strArr, s => s.Equals(temp))) {
return true;
} else {
return false;
}
}
}
HTH

Resources