Search data in Observable - mongodb

I'd like to have a search input, that display the result on keypress.
At the moment, this is what I have :
mylist: Observable<MyData[]>;
term = new FormControl();
ngOnInit() {
this.mylist = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.searchData(term));
}
searchData(valueToSearch:string){
if(valueToSearch == ''){
this.channels = MyData.find();
}
return MyData.find({'title':new RegExp(valueToSearch)});
}
It works quite well, but I have trouble to initialize "mylist", and I think my method isn't performant at all.
Basically, I want when my component is initialize, that:
this.mylist = MyData.find();
And on keypress, I want my search to be done on this.mylist, to avoid doing too much request.
Is it possible ?
I hope I'm clear.
Thanks by advance guys.

You must subscribe to the mapped data. Modify to the below code
this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.searchData(term))
.subscribe((result) => {
this.mylist = result
});;
#Julia is correct , modify your searchData() function as below
searchData(valueToSearch:string):Observable<any> {
if(valueToSearch == ''){
this.channels = MyData.find();
}
return <Observable<any>>MyData.find({'title':new RegExp(valueToSearch)});
}

Related

Update a BuiltList from built_value

I want to update the BuiltList in the state if some condition is met. Here is my reducer
TravelDeductionsStateBuilder _travelDeductionBreakfastToggled(
TravelDeductionsStateBuilder state,
TravelDeductionBreakfastToggledAction action) =>
state
..days = state.days.build().rebuild((d) {
if (d[action.key].deductions.contains(TravelDeductionType.BREAKFAST)) {
d[action.key]
.deductions
.rebuild((p0) => p0.remove(TravelDeductionType.BREAKFAST));
} else {
d[action.key]
.deductions
.rebuild((p0) => p0.add(TravelDeductionType.BREAKFAST));
}
}).toBuilder();
I need to add/remove ENUM entry into deductions but it seems that this update is ignored and I am not able to update this list accordingly. Any tips of what may be wrong?
If anyone wonders this is the solution
TravelDeductionsStateBuilder _travelDeductionBreakfastToggled(
TravelDeductionsStateBuilder state,
TravelDeductionBreakfastToggledAction action) =>
state
..days = state.days.build().rebuild((d) {
if (d[action.index]
.deductions
.contains(TravelDeductionType.BREAKFAST)) {
d[action.index] = d[action.index].rebuild(
(b) => b.deductions.remove(TravelDeductionType.BREAKFAST));
} else {
d[action.index] = d[action.index]
.rebuild((b) => b.deductions.add(TravelDeductionType.BREAKFAST));
}
}).toBuilder();
You can find the explanation here https://github.com/google/built_collection.dart/issues/259#issuecomment-1122390601

"map.getOrDefault" equivalent in Dart

I'm working on a friend suggestion algorithm for a flutter social media application. I'm still an amateur when it comes to Dart so I'm stuck on the following line of code:
class FriendSuggestionAlgorithm {
User friendSuggestion(User user) {
int max = -1;
User suggestion;
Map<User, int> map = new HashMap();
for (User friend in user.friends) {
for (User mutualFriend in friend.friends) {
if (mutualFriend.id != user.id && !user.friends.contains(mutualFriend)) {
map.putIfAbsent(mutualFriend, map.getOrDefault(mutual, 0) + 1);
}
}
}
for (MapEntry<User, int> mutualFriend in map.entries) {
if (mutualFriend.value > max) {
max = mutualFriend.value;
suggestion = mutualFriend.key;
}
}
return suggestion;
}
}
map.getOrDefault is underlined (I know the method doesn't exist in Dart). Do you know what the equivalent is in Dart? (PS, I'm just translating Java code into Dart.
Any help is appreciated!
Your code doesn't make sense. map.putIfAbsent will do work only if the key doesn't exist, so the hypothetical map.getOrDefault call with the same key would always return the default value anyway. That is, your logic would be the equivalent of map.putIfAbsent(mutual, () => 1), where nothing happens if the key already exists.
Map.putifAbsent takes a callback as its argument to avoid evaluating it unless it's actually necessary. I personally prefer using ??= when the Map values are non-nullable.
I presume that you actually want to increment the existing value, if one exists. If so, I'd replace the map.putIfAbsent(...) call with:
map[mutual] = (map[mutual] ?? 0) + 1;
Also see: Does Dart have something like defaultdict in Python?
You could do it like this:
map.putIfAbsent(mutual, (map.containsKey(mutual) ? map[mutual] : 0) + 1)
Maybe take a look at this for more info: https://dart.dev/guides/language/language-tour#conditional-expressions
Edit:
This code should work
class FriendSuggestionAlgorithm {
User? friendSuggestion(User user) {
int max = -1;
User? suggestion;
Map<User, int> map = {};
for (User friend in user.friends) {
for (User mutualFriend in friend.friends) {
if (mutualFriend.id != user.id && !user.friends.contains(mutualFriend)) {
map.putIfAbsent(mutualFriend, () => (map[mutualFriend] ?? 0) + 1);
}
}
}
for (MapEntry<User, int> mutualFriend in map.entries) {
if (mutualFriend.value > max) {
max = mutualFriend.value;
suggestion = mutualFriend.key;
}
}
return suggestion;
}
}
Note that suggestion nullable because it could happen that suggestion is never assigned. And therefore friendSuggestion(user) can return null;
To come back to your question
the correct code is
map.putIfAbsent(mutualFriend, () => (map[mutualFriend] ?? 0) + 1);
My mistake on my original answer, the ifAbsent part of this is a function. In the function the value of mutualFriend is retrieved. If that is null use 0.

AG Grid: Better way for validation row - valueSetter?

Is there a better way to validate a row in ag-grid than with valueSetter?
I can achieve the validation with that but I am not sure, if there is a better way.
https://www.ag-grid.com/javascript-grid-value-setters/#properties-for-setters-and-parsers
I want to validate two fields in the row. DateFrom and DateUntil (they are not allow to be null and DateFrom must be lower than DateUntil).
There are two ways of possible validation handling:
First: via ValueSetter function
and
Second: via custom cellEditor component
I suggest that it would be better to split the logic between custom components, but as you said you need to validate two cell-values between themselves.
On this case from UI perspective you could try to combine them inside one cell and it would be easily to work with values via one component only.
You could override the valueSetter and call the grid api transaction update instead.
Here is pseudo-code that shows how you could implement this.
valueSetter: params => {
validate(params.newValue, onSuccess, onFail);
return false;
};
validate = (newvalue, success, fail) => {
if (isValid(newValue)) {
success();
} else {
fail();
}
};
onSuccess = () => {
// do transaction update to update the cell with the new value
};
onFail = () => {
// update some meta data property that highlights the cell signalling that the value has failed to validate
};
This way you can also do asynchronous validation.
Here is a real example of an async value setter that has success, failure, and while validating handlers that do transaction updates when validation is done.
const asyncValidator = (
newValue,
validateFn,
onWhileValidating,
onSuccess,
_onFail
) => {
onWhileValidating();
setTimeout(function() {
if (validateFn(newValue)) {
onSuccess();
} else {
_onFail();
}
}, 1000);
};
const _onWhileValidating = params => () => {
let data = params.data;
let field = params.colDef.field;
data[field] = {
...data[field],
isValidating: true
};
params.api.applyTransaction({ update: [data] });
};
const _onSuccess = params => () => {
let data = params.data;
let field = params.colDef.field;
data[field] = {
...data[field],
isValidating: false,
lastValidation: true,
value: params.newValue
};
params.api.applyTransaction({ update: [data] });
};
const _onFail = params => () => {
let data = params.data;
let field = params.colDef.field;
data[field] = {
...data[field],
isValidating: false,
lastValidation: params.newValue
};
params.api.applyTransaction({ update: [data] });
};
const asyncValidateValueSetter = validateFn => params => {
asyncValidator(
params.newValue,
validateFn,
_onWhileValidating(params),
_onSuccess(params),
_onFail(params)
);
return false;
};
Here is a code runner example showing this in action: https://stackblitz.com/edit/async-validation-ag-grid-final
Have a look at this two snippets, these come from our internal knowledge base (accessible to customers)
When editing a value in column 'A (Required)', you will see that it does not allow you to leave it empty. If you leave it empty and return the edit, it will be cancelled.
//Force Cell to require a value when finished editing
https://plnkr.co/edit/GFgb4v7P8YCW1PxJwGTx?p=preview
In this example, we are using a Custom Cell Editor that will also validate the values against a 6 character length rule. While editing, if the value is modified outside of 6 characters, it will appear in red, and when you stop editing the row, the value would be reset, so it only accepts a complete edit if the value is valid.
//Inline Validation while editing a cell
https://plnkr.co/edit/dAAU8yLMnR8dm4vNEa9T?p=preview

Angular 2 - forkJoin can't bind the correct lass

I'm trying to do multiple ajax calls together.
I can't figure out what is wrong with these lines. Seems like the second input of the subscribe function is processed as Group[] instead of Authorization[]
Observable.forkJoin(
[this.userService.getAllGroups(),this.userService.getAllAuthorizations()]
)
.subscribe(
([groups,authorizations]) => {
this.groups = groups;
this.authorizations = authorizations; //error: Type 'Group[]' is not assignable to type 'Authorization[]'
this.loaderService.hideLoader();
},
(err)=>{
this.loaderService.hideLoader();
}
);
Interfaces are:
(method) UserService.getAllGroups(): Observable<Group[]>
(method) UserService.getAllAuthorizations(): Observable<Authorization[]>
Anyone can help me understand what the is problem?
Try it like this:
Observable.forkJoin<Group[], Authorization[]>(
this.userService.getAllGroups(),
this.userService.getAllAuthorizations()
).subscribe(results => {
this.groups = results[0];
this.authorizations = results[1];
);
or
Observable.forkJoin<Group[], Authorization[]>(
this.userService.getAllGroups(),
this.userService.getAllAuthorizations()
).subscribe((groups, authorizations) => {
this.groups = groups;
this.authorizations = authorizations;
);

tinymce.dom.replace throws an exception concerning parentNode

I'm writing a tinyMce plugin which contains a section of code, replacing one element for another. I'm using the editor's dom instance to create the node I want to insert, and I'm using the same instance to do the replacement.
My code is as follows:
var nodeData =
{
"data-widgetId": data.widget.widgetKey(),
"data-instanceKey": "instance1",
src: "/content/images/icon48/cog.png",
class: "widgetPlaceholder",
title: data.widget.getInfo().name
};
var nodeToInsert = ed.dom.create("img", nodeData);
// Insert this content into the editor window
if (data.mode == 'add') {
tinymce.DOM.add(ed.getBody(), nodeToInsert);
}
else if (data.mode == 'edit' && data.selected != null) {
var instanceKey = $(data.selected).attr("data-instancekey");
var elementToReplace = tinymce.DOM.select("[data-instancekey=" + instanceKey + "]");
if (elementToReplace.length === 1) {
ed.dom.replace(elementToReplace[0], nodeToInsert);
}
else {
throw new "No element to replace with that instance key";
}
}
TinyMCE breaks during the replace, here:
replace : function(n, o, k) {
var t = this;
if (is(o, 'array'))
n = n.cloneNode(true);
return t.run(o, function(o) {
if (k) {
each(tinymce.grep(o.childNodes), function(c) {
n.appendChild(c);
});
}
return o.parentNode.replaceChild(n, o);
});
},
..with the error Cannot call method 'replaceChild' of null.
I've verified that the two argument's being passed into replace() are not null and that their parentNode fields are instantiated. I've also taken care to make sure that the elements are being created and replace using the same document instance (I understand I.E has an issue with this).
I've done all this development in Google Chrome, but I receive the same errors in Firefox 4 and IE8 also. Has anyone else come across this?
Thanks in advance
As it turns out, I was simply passing in the arguments in the wrong order. I should have been passing the node I wanted to insert first, and the node I wanted to replace second.