Filtering a list according to a parameter in Angular / IONIC 4 - json

I have this function that returns a list of pokemons from a JSON URL of pokeapi.
I need to filter this function so that it shows those of a certain type that I bring with the variable dataPoke.
The variable is returned with the correct value, but I don't know how to give it filtered output and that it only shows the pokemons of the dataPoke type.
I get data from https://pokeapi.co/api/v2/pokemon https://pokeapi.co/api/v2/pokemon/3
listadoPokemonFiltrado(salida = 0,dataPoke) {
console.log("datos recibidos: ", dataPoke);
return this.http.get(`${this.baseUrl}/pokemon?salida=${salida}`)
.pipe(
map(result => { return result['results'];}),
map(pokemon => {
return pokemon.map((arreglo, index) => {
arreglo.image = this.obtenerImagen(salida + index + 1);
arreglo.pokeIndex = salida + index + 1;
arreglo.type = this.obtenerTypo(dataPoke);
arreglo.pokeIndex = arreglo.type;
return arreglo;
});
})
);
}
obtenerImagen(index) {
return `${this.imageUrl}${index}.png`;
}
obtenerTypo(index) {
return `${this.baseUrlTypes}/${index}`;
}

Reading code not in English is certainly a challenge, but I assume that what you're looking for is filtering your array?
listadoPokemonFiltrado(salida = 0, dataPoke) {
console.log('datos recibidos: ', dataPoke);
return this.http.get(`${this.baseUrl}/pokemon?salida=${salida}`).pipe(
map(result => result['results']),
map(pokemons => {
return pokemons
.filter(pokemon => pokemon.type === dataPoke)
.map((arreglo, index) => {
arreglo.image = this.obtenerImagen(salida + index + 1);
arreglo.pokeIndex = salida + index + 1;
arreglo.type = this.obtenerTypo(dataPoke);
arreglo.pokeIndex = arreglo.type;
return arreglo;
});
})
);
}
obtenerImagen(index) {
return `${this.imageUrl}${index}.png`;
}
obtenerTypo(index) {
return `${this.baseUrlTypes}/${index}`;
}
I have added .filter(pokemon => pokemon.type === dataPoke) to filter results array.

Related

Unable to access inner JSON value in JSON array - Typescript(Using Angular 8)

I am trying to use the group by function on a JSON array using the inner JSON value as a key as shown below. But unable to read the inner JSON value. Here is my JSON array.
NotificationData = [
{
"eventId":"90989",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{
"externalId":"2434",
"priority":"1"
}
}
},
{
"eventId":"6576",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{
"externalId":"78657",
"priority":"1"
}
}
}
]
GroupBy Logic:
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
return result;
}, {});
};
const serviceOrdersGroupedByExternalId = groupBy(this.NotificationData, 'event.ServiceOrder.externalId');
//this line of code is not working as
// it is unable to locate the external id value.
Desired output
{ "2434":[{
"eventId":"90989",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{ "priority":"1" }
}
}],
"78657":[{
"eventId":"6576",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{ "priority":"1" }
}
}]
}
Does this solves your purpose?
let group = NotificationData.reduce((r, a) => {
let d = r[a.event.ServiceOrder.externalId] = [...r[a.event.ServiceOrder.externalId] || [], a];
return r;
}, {});
console.log(group);
Try like this:
result = {};
constructor() {
let externalIds = this.NotificationData.flatMap(item => item.event.ServiceOrder.externalId);
externalIds.forEach(id => {
var eventData = this.NotificationData.filter(
x => x.event.ServiceOrder.externalId == id
).map(function(item) {
delete item.event.ServiceOrder.externalId;
return item;
});
this.result[id] = eventData;
});
}
Working Demo

Angular 6 . I Want to change the interval dynamically according to the value given in the array

This is my set-interval and I want to change the interval dynamically according to the value given in the array.
setInterval(() => {
this.getwebsiteurl();
this.count++;
if (this.count > this.data1.length) {
this.count = 0;
}
}, this.filtered[this.count].timeout);
getwebsiteurl() {
if (this.count < this.data1.length) {
this.http
.get("assets/" + this.len + "/" + this.data1[this.count].HtmlName + ".html", {
responseType: "text"
})
.subscribe((data: any) => {
this.htmlfile = data;
});
}
}
Filtered Array contains

Object from Observable then Array from Observable inside a foreach. how to order it?Asynchronous Angular 4/5

Here is my problem.
I'm running a method that sends me a json (method = myTableService.getAllTables ()), to create an object (object = this.myTables).
Then I execute the method for each, for each element of this.myTables I execute a new request (request = this.myTableService.getTableStatut (element.theId)).
I retrieve data from a new json to create an object (object = myTableModel).
Each result will be added to this.myTableListProvisory.
The problem is the order of execution.
It execute the console.log before the end of the for each...
This.myTableListProvisory.length and this.myTableList.length return 0.
How to wait for the end of the for each run before running the console.log?
Thank you
ngOnInit() {
this.myTableService.getAllTables()
.subscribe(data => {
this.myTables = data;
this.myTableList = this.getAllTableStatut(this.myTables);
console.log("this.myTableList.length : " + this.myTableList.length);
}, err => {
console.log(err);
})
}
getAllTableStatut(myTables: any) {
this.myTableListProvisoire = [];
myTables.forEach(element => {
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
})
console.log("this.myTableListProvisoire.length : " + this.myTableListProvisoire.length);
})
return this.myTableListProvisoire;
}
Result of console.log
this.myTableListProvisoire.length : 0
this.myTableList.length : 0
UPDATE
I have simplified the code ... I put it in its entirety for the understanding. What I need is to sort the array after it is done. The problem is that I don't know how to use a flatMap method in a query inside a foreach ... I have temporarily placed the sort method inside the subscribe which is a bad solution for the performance. That's why I want to do my sort after the creation of the array. Thank you
export class MyTableComponent implements OnInit {
myTables: any;
statut: any;
myTableModel: MyTableModel;
myTableList: Array<MyTableModel>;
myTableListProvisoire: Array<MyTableModel>;
i: number;
j: number;
myTableModelProvisoire: MyTableModel = null;
constructor(public myTableService: MyTableService) { }
ngOnInit() {
this.myTableService.getAllTables()
.subscribe(data => {
this.myTables = data;
this.myTableList = this.getAllTableStatut(this.myTables);
}, err => {
console.log(err);
})
}
getAllTableStatut(myTables: any) {
this.myTableListProvisoire = [];
myTables.forEach(element => {
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
for (this.j = 0; this.j < this.myTableListProvisoire.length; this.j++) {
for (this.i = 0; this.i < this.myTableListProvisoire.length - 1; this.i++) {
if (this.myTableListProvisoire[this.i].getTableNumber() > this.myTableListProvisoire[(this.i + 1)].getTableNumber()) {
this.myTableModelProvisoire = this.myTableListProvisoire[this.i];
this.myTableListProvisoire[this.i] = this.myTableListProvisoire[(this.i + 1)];
this.myTableListProvisoire[(this.i + 1)] = this.myTableModelProvisoire;
}
}
}
}, err => {
console.log(err);
})
}, err => {
console.log(err);
})
return this.myTableListProvisoire;
}
}
Well Observables are asynchronous actions and will be executed after finishing the current execution block. So when the js engine comes to your
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
})
it will only create a subscription, but the code inside of it will be executed after all the other code in the block. So that's why your console.log is being executed before you get any data. So you need to place it inside the .subscribe block to see the. I think there can be a better solution to get the data, but I don't know the structure of the app, so I can't advice. If you create an example on https://stackblitz.com/ I could probably help you out with a better solution.

Transform Request to Autoquery friendly

We are working with a 3rd party grid (telerik kendo) that has paging/sorting/filtering built in. It will send the requests in a certain way when making the GET call and I'm trying to determine if there is a way to translate these requests to AutoQuery friendly requests.
Query string params
Sort Pattern:
sort[{0}][field] and sort[{0}][dir]
Filtering:
filter[filters][{0}][field]
filter[filters][{0}][operator]
filter[filters][{0}][value]
So this which is populated in the querystring:
filter[filters][0][field]
filter[filters][0][operator]
filter[filters][0][value]
would need to be translated to.
FieldName=1 // filter[filters][0][field]+filter[filters][0][operator]+filter[filters][0][value] in a nutshell (not exactly true)
Should I manipulate the querystring object in a plugin by removing the filters (or just adding the ones I need) ? Is there a better option here?
I'm not sure there is a clean way to do this on the kendo side either.
I will explain the two routes I'm going down, I hope to see a better answer.
First, I tried to modify the querystring in a request filter, but could not. I ended up having to run the autoqueries manually by getting the params and modifying them before calling AutoQuery.Execute. Something like this:
var requestparams = Request.ToAutoQueryParams();
var q = AutoQueryDb.CreateQuery(requestobject, requestparams);
AutoQueryDb.Execute(requestobject, q);
I wish there was a more global way to do this. The extension method just loops over all the querystring params and adds the ones that I need.
After doing the above work, I wasn't very happy with the result so I investigated doing it differently and ended up with the following:
Register the Kendo grid filter operations to their equivalent Service Stack auto query ones:
var aq = new AutoQueryFeature { MaxLimit = 100, EnableAutoQueryViewer=true };
aq.ImplicitConventions.Add("%neq", aq.ImplicitConventions["%NotEqualTo"]);
aq.ImplicitConventions.Add("%eq", "{Field} = {Value}");
Next, on the grid's read operation, we need to reformat the the querystring:
read: {
url: "/api/stuff?format=json&isGrid=true",
data: function (options) {
if (options.sort && options.sort.length > 0) {
options.OrderBy = (options.sort[0].dir == "desc" ? "-" : "") + options.sort[0].field;
}
if (options.filter && options.filter.filters.length > 0) {
for (var i = 0; i < options.filter.filters.length; i++) {
var f = options.filter.filters[i];
console.log(f);
options[f.field + f.operator] = f.value;
}
}
}
Now, the grid will send the operations in a Autoquery friendly manner.
I created an AutoQueryDataSource ts class that you may or may not find useful.
It's usage is along the lines of:
this.gridDataSource = AutoQueryKendoDataSource.getDefaultInstance<dtos.QueryDbSubclass, dtos.ListDefinition>('/api/autoQueryRoute', { orderByDesc: 'createdOn' });
export default class AutoQueryKendoDataSource<queryT extends dtos.QueryDb_1<T>, T> extends kendo.data.DataSource {
private constructor(options: kendo.data.DataSourceOptions = {}, public route?: string, public request?: queryT) {
super(options)
}
defer: ng.IDeferred<any>;
static exportToExcel(columns: kendo.ui.GridColumn[], dataSource: kendo.data.DataSource, filename: string) {
let rows = [{ cells: columns.map(d => { return { value: d.field }; }) }];
dataSource.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
//push single row for every record
rows.push({
cells: _.map(columns, d => { return { value: data[i][d.field] } })
})
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: _.map(columns, d => { return { autoWidth: true } }),
// Title of the sheet
title: filename,
// Rows of the sheet
rows: rows
}
]
});
//save the file as Excel file with extension xlsx
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: filename });
})
}
static getDefaultInstance<queryT extends dtos.QueryDb_1<T>, T>(route: string, request: queryT, $q?: ng.IQService, model?: any) {
let sortInfo: {
orderBy?: string,
orderByDesc?: string,
skip?: number
} = {
};
let opts = {
transport: {
read: {
url: route,
dataType: 'json',
data: request
},
parameterMap: (data, type) => {
if (type == 'read') {
if (data.sort) {
data.sort.forEach((s: any) => {
if (s.field.indexOf('.') > -1) {
var arr = _.split(s.field, '.')
s.field = arr[arr.length - 1];
}
})
}//for autoquery to work, need only field names not entity names.
sortInfo = {
orderByDesc: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'desc'), 'field'), ','),
orderBy: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'asc'), 'field'), ','),
skip: 0
}
if (data.page)
sortInfo.skip = (data.page - 1) * data.pageSize,
_.extend(data, request);
//override sorting if done via grid
if (sortInfo.orderByDesc) {
(<any>data).orderByDesc = sortInfo.orderByDesc;
(<any>data).orderBy = null;
}
if (sortInfo.orderBy) {
(<any>data).orderBy = sortInfo.orderBy;
(<any>data).orderByDesc = null;
}
(<any>data).skip = sortInfo.skip;
return data;
}
return data;
},
},
requestStart: (e: kendo.data.DataSourceRequestStartEvent) => {
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if ($q)
ds.defer = $q.defer();
},
requestEnd: (e: kendo.data.DataSourceRequestEndEvent) => {
new DatesToStringsService().convert(e.response);
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if (ds.defer)
ds.defer.resolve();
},
schema: {
data: (response: dtos.QueryResponse<T>) => {
return response.results;
},
type: 'json',
total: 'total',
model: model
},
pageSize: request.take || 40,
page: 1,
serverPaging: true,
serverSorting: true
}
let ds = new AutoQueryKendoDataSource<queryT, T>(opts, route, request);
return ds;
}
}

How to rebind Json object with Telerik MVC grid

Im having problem with rebinding grid with Json object….
Im trying to create custom delete button…
So far I have Jquery function: Gets an ID of selected column (username) and call controller action “UserDetails”
Delete button:
$("#DeleteUser").click(function () {
if (id != "") {
var answer = confirm("Delete user " + id)
if (answer) {
$.ajax({
type: "POST",
url: "/Admin/UserDetails",
data: "deleteName=" + id,
success: function (data) {
}
});
}
} else {
$("#erorMessage").html("First you must select user you whant to delete!");
}
});
This is action controller UserDetails(string startsWith, string deleteName)
[GridAction]
public ActionResult UserDetails(string startsWith, string deleteName)
{ // Custom search...
if (!string.IsNullOrEmpty(startsWith))
{
return GetSearchUserResult(startsWith);
}
if (!string.IsNullOrEmpty(deleteName))
{
TblUserDetails user = db.TblUserDetails.Single(a => a.TblUser.userName == deleteName);
try
{
TblUser userToDelete = db.TblUser.Single(a => a.userId == user.TblUser.userId);
db.DeleteObject(user);
db.DeleteObject(userToDelete);
db.SaveChanges();
Membership.DeleteUser(deleteName);
List<UserDto> retModelData = new List<UserDto>();
//GetAllUsers() returns a List<UserDto> of users.
retModelData = GetAllUsers();
var model = new GridModel
{
Data = retModelData,
Total = GetAllUsers().Count()
};
return View(model);
}
catch
{
return View(new GridModel());
}
}
else
{
var user = GetAllUsers();
return View(new GridModel(user));
}
}
So far everything is working OK. But can I bind my grid with these Json data and how???
This is my Json result that I want to bind with grid...
And here is my grid:
#(Html.Telerik().Grid<App.Web.Models.UserDto>()
.Name("Grid")
.DataKeys(key =>
{
key.Add(a => a.Id);
})
.Columns(column =>
{
column.Bound(a => a.Username).Filterable(false);
column.Bound(a => a.FirstName).Filterable(false);
column.Bound(a => a.LastName).Filterable(false);
column.Bound(a => a.Email).Filterable(false);
})
.DetailView(detailView => detailView.ClientTemplate(
"<table id='DetailTable'><tbody><tr class='UserRow'><td class='Tbllable'><b>First name</b></td><td><#= FirstName #></td>"
+ "<td></td><td></td>"
+ "</tr><tr><td class='Tbllable'><b>Last name</b></td>"
+ "<td><#= LastName #></td>"
+ "<td id='Roles'></td><td id='Operations'></td>"
+ "</tr><tr><td class='Tbllable'><b>Username</b></td><td><#= Username #></td></tr><tr><td class='Tbllable'><b>Address</b></td>"
+ "<td><#= Address #></td></tr><tr><td class='Tbllable'><b>Email</b></td><td><#= Email #></td></tr><tr><td class='Tbllable'><b>Birth date</b></td>"
+ "<td></td></tr><tr><td class='Tbllable'><b>Registration date</b></td><td></td></tr><tr><td class='Tbllable'><b>Phone number</b></td>"
+ "<td><#= PhoneNumberHome #></td></tr><tr><td class='Tbllable'><b>Mobile number</b></td><td><#= PhoneNumberMobile #></td></tr></tbody></table>"
))
//.EnableCustomBinding(true)
.DataBinding(bind => bind.Ajax().Select("UserDetails", "Admin", new { startsWith = ViewBag.startsWith }))
.Pageable(paging =>
paging.PageSize(12)
.Style(GridPagerStyles.NextPreviousAndInput)
.Position(GridPagerPosition.Bottom)
)
.ClientEvents(e => e
.OnRowDataBound("Expand")
.OnRowSelect("select")
.OnLoad("replaceConfirmation")
)
.RowAction(row =>
{
if (row.Index == 0)
{
row.DetailRow.Expanded = true;
}
})
.Editable(editing => editing.Mode(GridEditMode.PopUp))
.Selectable()
.Sortable()
)