I trying to use the Riot API for Champions in this code
--Service
#Injectable()
export class ChampionService {
private riotUrl = 'https://br1.api.riotgames.com/lol/static-
data/v3/champions?api_key=myApiKey';
constructor(private _http: Http) { }
getChampion(): Observable<Champion[]> {
return this._http.get(this.riotUrl)
.map((res:Response) => <Champion[]>[res.json()])
.do(data => console.log(JSON.stringify(data)));
}}
-- Component
export class ChampionListComponent{
errorMessage: string;
champions: Champion[];
constructor(private _ChampionService: ChampionService){}
ngOnInit():void{
this._ChampionService.getChampion()
.subscribe(champions => this.champions = champions,
error => this.errorMessage = <any>error);}
--HTML
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let champion of champions'>
<td>{{champion.id}}</td>
<td>{{champion.name}}</td>
</tr>
</tbody>
</table>
In the console that's appears correctly.. but nothing happen with my table
--- My Console Show This
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
champion-list.service.ts:18 [{"type":"champion","version":"7.8.1","data":{"Jax":{"id":24,"key":"Jax","name":"Jax","title":"o Grão-Mestre das Armas"},"Sona":{"id":37,"key":"Sona","name":"Sona","title":"a Mestra das Cordas"},"Tristana":{"id":18,"key":"Tristana","name":"Tristana","title":"a Artilheira Yordle"},"Varus":{"id":110,"key":"Varus","name":"Varus","title":"a Flecha da Vingança"},"Fiora":{"id":114,"key":"Fiora","name":"Fiora","title":"a Grande Duelista"},"Singed":{"id":27,"key":"Singed","name":"Singed","title":"o Químico Louco"},"TahmKench":{"id":223,"key":"TahmKench","name":"Tahm Kench","title":"o Rei do Rio"},"Leblanc":{"id":7,"key":"Leblanc","name":"LeBlanc","title":"a Farsante"},"Thresh":{"id":412,"key":"Thresh","name":"Thresh","title":"o Guardião das Correntes"},"Karma":{"id":43,"key":"Karma","name":"Karma","title":"a Iluminada"},"Jhin":{"id":202,"key":"Jhin","name":"Jhin","title":"o Virtuoso"},"Rumble":{"id":68,"key":"Rumble","name":"Rumble","title":"a Ameaça Mecânica"},"Udyr":{"id":77,"key":"Udyr","name":"Udyr","title":"o Andarilho Espiritual"},"LeeSin":{"id":64,"key":"LeeSin","name":"Lee Sin","title":"o Monge Cego"},"Yorick":{"id":83,"key":"Yorick","name":"Yorick","title":"Pastor de Almas"},"Kassadin":{"id":38,"key":"Kassadin","name":"Kassadin","title":"o Andarilho do Vazio"},"Sivir":{"id":15,"key":"Sivir","name":"Sivir","title":"a Mestra da Batalha"},"MissFortune":{"id":21,"key":"MissFortune","name":"Miss Fortune","title":"a Caçadora de Recompensas"}...
someone can help me ? Sorry for the long post
Even though you are setting your response in an array:
.map((res:Response) => <Champion[]>[res.json()])
This still means that your array just contains one object, that contains objects (which you want to iterate). So first let's remove the assignment to an array, and instead step into the JSON and extract the object that contains your objects that you want:
.map((res:Response) => res.json().data)
This means you end up with an object with your objects. Since object cannot be iterated, we need to use a pipe:
#Pipe({ name: 'keys', pure: false })
export class KeysPipe implements PipeTransform {
transform(value: any, args?: any[]): any[] {
// create instance vars to store keys and final output
let keyArr: any[] = Object.keys(value),
dataArr = [];
// loop through the object,
// pushing values to the return array
keyArr.forEach((key: any) => {
dataArr.push(value[key]);
});
// return the resulting array
return dataArr;
}
}
Then apply that pipe in your template:
<tr *ngFor='let champion of champions | keys'>
<td>{{champion.id}}</td>
<td>{{champion.name}}</td>
</tr>
That should do the trick! :)
As a sidenote, this means your response is not an Array of Champion, so assigning it <Champion[]> is inaccurate. However your interface is built, you need to make the appropriate changes.
Demo
Related
I'm trying to filter table rows in an intelligent way (as opposed to just tons of code that get the job done eventually) but a rather dry of inspiration.
I have 5 columns in my table. At the top of each there is either a dropdown or a textbox with which the user may filter the table data (basically hide the rows that don't apply)
There are plenty of table filtering plugins for jQuery but none that work quite like this, and thats the complicated part :|
Here is a basic filter example http://jsfiddle.net/urf6P/3/
It uses the jquery selector :contains('some text') and :not(:contains('some text')) to decide if each row should be shown or hidden. This might get you going in a direction.
EDITED to include the HTML and javascript from the jsfiddle:
$(function() {
$('#filter1').change(function() {
$("#table td.col1:contains('" + $(this).val() + "')").parent().show();
$("#table td.col1:not(:contains('" + $(this).val() + "'))").parent().hide();
});
});
Slightly enhancing the accepted solution posted by Jeff Treuting, filtering capability can be extended to make it case insensitive. I take no credit for the original solution or even the enhancement. The idea of enhancement was lifted from a solution posted on a different SO post offered by Highway of Life.
Here it goes:
// Define a custom selector icontains instead of overriding the existing expression contains
// A global js asset file will be a good place to put this code
$.expr[':'].icontains = function(a, i, m) {
return $(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
// Now perform the filtering as suggested by #jeff
$(function() {
$('#filter1').on('keyup', function() { // changed 'change' event to 'keyup'. Add a delay if you prefer
$("#table td.col1:icontains('" + $(this).val() + "')").parent().show(); // Use our new selector icontains
$("#table td.col1:not(:icontains('" + $(this).val() + "'))").parent().hide(); // Use our new selector icontains
});
});
This may not be the best way to do it, and I'm not sure about the performance, but an option would be to tag each column (in each row) with an id starting with a column identifier and then a unique number like a record identifier.
For example, if you had a column Produce Name, and the record ID was 763, I would do something like the following:
<table id="table1">
<thead>
<tr>
<th>Artist</th>
<th>Album</th>
<th>Genre</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td id="artist-127">Red Hot Chili Peppers</td>
<td id="album-195">Californication</td>
<td id="genre-1">Rock</td>
<td id="price-195">$8.99</td>
</tr>
<tr>
<td id="artist-59">Santana</td>
<td id="album-198">Santana Live</td>
<td id="genre-1">Rock</td>
<td id="price-198">$8.99</td>
</tr>
<tr>
<td id="artist-120">Pink Floyd</td>
<td id="album-183">Dark Side Of The Moon</td>
<td id="genre-1">Rock</td>
<td id="price-183">$8.99</td>
</tr>
</tbody>
</table>
You could then use jQuery to filter based on the start of the id.
For example, if you wanted to filter by the Artist column:
var regex = /Hot/;
$('#table1').find('tbody').find('[id^=artist]').each(function() {
if (!regex.test(this.innerHTML)) {
this.parentNode.style.backgroundColor = '#ff0000';
}
});
You can filter specific column by just adding children[column number] to JQuery filter. Normally, JQuery looks for the keyword from all the columns in every row. If we wanted to filter only ColumnB on below table, we need to add childern[1] to filter as in the script below. IndexOf value -1 means search couldn't match. Anything above -1 will make the whole row visible.
ColumnA | ColumnB | ColumnC
John Doe 1968
Jane Doe 1975
Mike Nike 1990
$("#myInput").on("change", function () {
var value = $(this).val().toLowerCase();
$("#myTable tbody tr").filter(function () {
$(this).toggle($(this.children[1]).text().toLowerCase().indexOf(value) > -1)
});
});
step:1 write the following in .html file
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:40%;">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
</table>
step:2 write the following in .js file
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
I need to use angular material table without model, because I don't know what will come from service.
So I am initializing my MatTableDataSource and displayedColumns dynamically in component like that :
TableComponent :
ngOnInit() {
this.vzfPuanTablo = [] //TABLE DATASOURCE
//GET SOMETHING FROM SERVICE
this.listecidenKisi = this.listeciServis.listecidenKisi;
this.listecidenVazife = this.listeciServis.listecidenVazife;
//FILL TABLE DATASOURCE
var obj = {};
for (let i in this.listecidenKisi ){
for( let v of this.listecidenVazife[i].vazifeSonuclar){
obj[v.name] = v.value;
}
this.vzfPuanTablo.push(obj);
obj={};
}
//CREATE DISPLAYED COLUMNS DYNAMICALLY
this.displayedColumns = [];
for( let v in this.vzfPuanTablo[0]){
this.displayedColumns.push(v);
}
//INITIALIZE MatTableDataSource
this.dataSource = new MatTableDataSource(this.vzfPuanTablo);
}
The most important part of code is here :
for( let v in this.vzfPuanTablo[0]) {
this.displayedColumns.push(v);
}
I am creating displayedColumns here dynamically, it means; even I don't know what will come from service, I can show it in table.
For example displayedColumns can be like that:
["one", "two" , "three" , "four" , "five" ]
or
["stack","overflow","help","me]
But it is not problem because I can handle it.
But when I want to show it in HTML, I can't show properly because of
matCellDef thing:
TableHtml :
<mat-table #table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let disCol of displayedColumns; let colIndex = index" matColumnDef="{{disCol}}">
<mat-header-cell *matHeaderCellDef>{{disCol}}</mat-header-cell>
<mat-cell *matCellDef="let element "> {{element.disCol}}
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
My problem is here:
<mat-cell *matCellDef="let element "> {{element.disCol}} < / mat-cell>
In fact, I want to display element."disCol's value" in the cell, but I don't know how can I do that.
Otherwise, everything is ok except this element."disCol's value" thing.
When I use {{element.disCol}} to display value of element that has disCols's value , all cells are empty like that:
Other example that using {{element}} only:
Also as you can see:
Table datasource is changing dynamically. It means I can't use {{element.ColumnName}} easily, because I don't know even what is it.
First Example's displayedColumns = ['Vazife', 'AdSoyad', 'Kirmizi', 'Mavi', 'Yesil', 'Sari'];
Second Example's displayedColumns = ['Muhasebe', 'Ders', 'Egitim', 'Harici'];
matHeaderCellDef is correct , because it is using {{disCol}} directly.
But I need to read disCol's value, and display element.(disCol's value) in the cell.
How can I do that ?
I found solution :)
It is very very easy but i could't see at first :)
only like that :
<mat-cell *matCellDef="let element "> {{element[disCol]}}
</mat-cell>
I must use {{element[disCol]}} only in HTML.
Now , everything is ok:)
For a full working example based on #mevaka's
Where jobDetails$ is the array of items.
columns$ is equvilent to Object.keys(jobDetails$[0]) so is just a string[]
<table mat-table [dataSource]="jobDetails$ | async">
<ng-container *ngFor="let disCol of (columns$ | async); let colIndex = index" matColumnDef="{{disCol}}">
<th mat-header-cell *matHeaderCellDef>{{disCol}}</th>
<td mat-cell *matCellDef="let element">{{element[disCol]}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="(columns$ | async)"></tr>
<tr mat-row *matRowDef="let row; columns: (columns$ | async)"></tr>
</table>
I've tried my best to boil a dynamic table down to the minimum. This example will display any columns given an array of flat objects with any keys. Note how the first object has an extra "foo" property that causes an entire column to be created. The DATA const could be some data you get from a service. Also, you could add a "column ID -> label" mapping into this if you know some common property names you'll be getting the JSON. See the stachblitz here.
import {Component, ViewChild, OnInit} from '#angular/core';
const DATA: any[] = [
{position: 1, name: 'sdd', weight: 1.0079, symbol: 'H', foo: 'bar'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
{position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'}
];
#Component({
selector: 'dynamic-table-example',
styleUrls: ['dynamic-table-example.css'],
templateUrl: 'dynamic-table-example.html',
})
export class DynamicTableExample implements OnInit {
columns:Array<any>
displayedColumns:Array<any>
dataSource:any
ngOnInit() {
// Get list of columns by gathering unique keys of objects found in DATA.
const columns = DATA
.reduce((columns, row) => {
return [...columns, ...Object.keys(row)]
}, [])
.reduce((columns, column) => {
return columns.includes(column)
? columns
: [...columns, column]
}, [])
// Describe the columns for <mat-table>.
this.columns = columns.map(column => {
return {
columnDef: column,
header: column,
cell: (element: any) => `${element[column] ? element[column] : ``}`
}
})
this.displayedColumns = this.columns.map(c => c.columnDef);
// Set the dataSource for <mat-table>.
this.dataSource = DATA
}
}
<mat-table #table [dataSource]="dataSource">
<ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
<mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
<mat-cell *cdkCellDef="let row">{{ column.cell(row) }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
I have an object with arrays which is nothing but JSON reply from server which I converted into Object and now it looks like this (but lot of values into it):-
Object_return:{
name:[1,25,2,24,3,78],
age:[2,34,4,78]
}
here name and age is dynamic coming from the server, so I do not know what exact values coming there so I can not refer it while iterating through the for loop
<th v-for = "item in Object_return.name">
and also I want to show this in a DataTable so the first row should looks like this
------------------
1 25
-------
name 2 24
-------
3 78
--------------------
second row
---------------------
2 34
-------
age 4 78
------------------------
and so on and so forth for all the values coming from the server
Does someone have an idea how to do this
You can iterate over an object and get the key value as the second argument.
<tr v-for="val, key in Object_return">
Here, key will be the name of the property.
Then, since you want to group the arrays in pairs, I suggest a computed property to massage the data into the format you want.
Here is a working example.
console.clear()
new Vue({
el: "#app",
data:{
serverData: {
name:[1,25,2,24,3,78],
age:[2,34,4,78]
}
},
computed:{
massaged(){
return Object.keys(this.serverData).reduce((acc, val) => {
// split each array into pairs
const copy = [...this.serverData[val]]
let pairs = []
while (copy.length > 0)
pairs.push(copy.splice(0, 2))
// add the paired array to the return object
acc[val] = pairs
return acc
}, {})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<table>
<tr v-for="val, key in massaged">
<td>{{key}}</td>
<td>
<table>
<tr v-for="pair in val">
<td>{{pair[0]}}</td>
<td>{{pair[1]}}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
Everyone!
So I have a little problem with httpsession and I don't know how to fixed it. here is the problem.
I have a Class Person which has aset<Product> and I set that class person into
the request.getSession like this.
String email = getRequest().getParameter("email");
String credential = getRequest().getParameter("credential");
validEmail(email);
validCredential(credential);
if(existError()){
setValues(email, credential);;
forward(login);
return;
}
PersonService ps = serviceFactory.getService(PersonService.class);
boolean success = ps.validatePasswordAndEmail(email, credential);
if(success){
Person person = ps.getPersonByEmail(email);
getSession().setAttribute("person", person); here you can see the object person into the session
forward("/packed.jsp");
}else{
addError("Email or Credential is not valid!");
setValues(email, credential);
forward(login);
return;
}
After that if the users put their correct information they will come to another
file called packed.jsp and they are logged.
My problem is when I edit a product's person who are logged into the system. let me show my code here
The page called packed.jsp has a buttom where the person who are logged click
and then he comes to this servlet below
public class EditProductAction extends Action {
private String editProduct = "/edit_product.jsp";
private String packed = "/packed.jsp";
#Override
public void process() throws Exception {
Integer id = Integer.parseInt(getRequest().getParameter("id"));
String brand = getRequest().getParameter("brand");
String model = getRequest().getParameter("model");
String name = getRequest().getParameter("name");
String quantity = getRequest().getParameter("quantity");
String color = getRequest().getParameter("color");
String info = getRequest().getParameter("info");
ProductService ps = serviceFactory.getService(ProductService.class);
Product product = ps.getProductByID(id);
if(name == null){
getRequest().setAttribute("product",product);
forward(editProduct);
return;
}
product.setBrand(brand);
product.setModel(model);
product.setName(name);
product.setQuantity(Integer.parseInt(quantity));
product.setColor(color);
product.setInfo(info);
ps.update(product);
getResponse().sendRedirect(getRequest().getContextPath()+packed);
}
}
As you can see everything works fine but when I come back to the page packed.jsp
it doesn't show the product modyfied but in the database works fine, I mean the product has been modyfied. here packed.jsp
<div class="mainDiv">
<table border="1px" width="80%">
<tr>
<th>BRAND</th>
<th>MODEL</th>
<th>NAME</th>
<th>QUANTITY</th>
<th>COLOR</th>
<th>INFO</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
<c:choose>
<c:when test="${empty person.products}">
<tr>
<td colspan="8" align="center"><span>You don't have any product yet!</span></td>
</tr>
</c:when>
<c:otherwise>
<c:forEach var="p" items="${person.products}">
<c:url var="urlDel" value="servlet">
<c:param name="id" value="${p.id}" />
</c:url>
<c:url var="urlEdit" value="EditProduct.action">
<c:param name="id" value="${p.id}" />
</c:url>
<tr>
<td>${p.brand}</td>
<td>${p.model}</td>
<td>${p.name}</td>
<td>${p.quantity}</td>
<td>${p.color}</td>
<td>${p.info}</td>
<td><img src="<%=request.getContextPath()%>/images/edit.png"></td>
<td><img src="<%=request.getContextPath()%>/images/delete.png"></td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
I would like to change the product and then when I back to packed.jsp I want to see the product modyfied. Thank you very much everyone.
I found a solution by creating another class with those objects and then put it the session. It works.
I am using DOJO ItemFileReadStore with dojox.grid.DataGrid to show Data Inside a Grid
Please see the Image here
http://imageshare.web.id/viewer.php?file=kdfvrkmn6k7xafmi4jdy.jpg
EMployee.Java
public class Employee {
String name;
String dept;
// Setters and Getters
}
This is My Servlet
response.setContentType("text/x-json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
List list = new ArrayList();
Employee emp1 = new Employee();
Employee emp2 = new Employee();
emp1.setDept("CSE");
emp1.setName("Vamsi");
emp2.setDept("EEE");
emp2.setName("Raju");
list.add(emp1);
list.add(emp2);
List jsonresponse = new ArrayList();
for (int i = 0; i < list.size(); i++) {
JSONObject nextObject = new JSONObject();
nextObject.put("name", list.get(i));
jsonresponse.add(nextObject);
}
JSONObject json = new JSONObject();
json.put("label", "name");
json.put("items", jsonresponse.toArray());
response.getWriter().write(json.toString());
}
This is MY JSP Page
<body class=" claro ">
<span dojoType="dojo.data.ItemFileReadStore" jsId="store1" url="http://localhost:8080/Man/MyServlet2"></span>
<table dojoType="dojox.grid.DataGrid" store="store1"
style="width: 100%; height: 500px;">
<thead>
<tr>
<th width="150px" field="name">Name</th>
<th width="150px" field="dept">Dept</th>
</tr>
</thead>
</table>
Please see the Image here
http://imageshare.web.id/viewer.php?file=kdfvrkmn6k7xafmi4jdy.jpg
Please help , Thank you .
+1 for posting the server output (firebug screenshot) in your question. This makes a lot easier for people to help you - for example I can easily see that the data format is still not quite right. You are getting better at both dojo and stackoverflow, it seems!
Remember that the ItemFileReadStore expects the data to be in a particular format. Your servlet is producing:
{label: "name", items: [
{name: {dept: "CSE", name: "Vansi"}},
{name: {dept: "ABC", name: "Abcd"}}
]}
You see you are telling the store that each item's "name" is an object with some properties ("dept" and "name"). This is why the grid shows object Object in the name column. It should be:
{label: "name", items: [
{dept: "CSE", name: "Vansi"},
{dept: "ABC", name: "Abcd"}
]}
I'm not very good with java, but I believe only a small change in your servlet is required:
// The for loop that adds employees to jsonresponse.
for (int i = 0; i < list.size(); i++)
{
// Instead of adding the
Emloyee e = (Employee)list.get(i);
JSONObject nextObject = new JSONObject();
nextObject.put("name", e.getName());
nextObject.put("dept", e.getDept());
jsonresponse.add(nextObject);
}
In fact, it's possible that you can just do json.put("items", list.toArray()); instead of adding each employee to jsonresponse.