gpt4 book ai didi

Angular - Material 表,是否可以在不刷新整个表的情况下更新行?

转载 作者:太空狗 更新时间:2023-10-29 16:53:30 26 4
gpt4 key购买 nike

经过几周的谷歌搜索和到目前为止只有一个 Stackoverflown 问题,我终于设法使用 Material Table Component 构建了我的 Angular CRUD 应用程序。它显示来自后端 (JSON) 的数据,对于 CRUD 操作,我使用的是如图所示的对话框(这是编辑,抱歉克罗地亚语)。对话框可能不是最好的方式,内联编辑可能更好。但是,要添加新项目,您仍然需要对话框之类的东西。

enter image description here

我坚持的最后一件事是如何相应地更新表中的字段。因此,当您在对话框中按“保存”时,数据会在后端(在 MySQL 表中)更新,但不会在前端更新。目前我有一个丑陋的解决方法,每次当你进行更新时,它也会刷新整个表。

无论如何这里的代码:

表格组件:

export class BazaComponent implements OnInit {
....
constructor(public httpClient: HttpClient, public dialog: MatDialog) {
}

ngOnInit() {
this.loadData();
}

// TODO: Simplfy this...
addNew(ident: number, naziv: string, mt: number, kutija: number,
komada: number, jm: string, orginal: number, lokacija: number, napomena: string) {
console.log('add new clicked');
const dialogRef = this.dialog.open(AddDialogComponent, {
data: {ident: ident, naziv: naziv, mt: mt, kutija: kutija,
komada: komada, jm: jm, orginal: orginal, lokacija: lokacija, napomena: napomena }
});

dialogRef.afterClosed().subscribe(result => {
console.log(result);
if (result === 1) {
this.loadData(); // --> This is a temp workaround, every time when I do CRUD operation just redraw whole thing again
}
});
}

startEdit(id: number, ident: number, naziv: string, mt: number, kutija: number,
komada: number, jm: string, orginal: number, lokacija: number, napomena: string) {

const dialogRef = this.dialog.open(EditDialogComponent, {
data: {id: id, ident: ident, naziv: naziv, mt: mt, kutija: kutija,
komada: komada, jm: jm, orginal: orginal, lokacija: lokacija, napomena: napomena}
});

dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
this.loadData(); // --> This is a temp workaround, every time when I do CRUD operation just redraw whole thing again
}
});
}

deleteItem(id: number, ident: number, naziv: string, mt: number) {
const dialogRef = this.dialog.open(DeleteDialogComponent, {
data: {id: id, ident: ident, naziv: naziv, mt: mt}
});

dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
this.loadData();
}
});
}


public loadData() {
this.exampleDatabase = new DataService(this.httpClient);
this.dataSource = new ExampleDataSource(this.exampleDatabase, this.paginator, this.sort);
Observable.fromEvent(this.filter.nativeElement, 'keyup')
.debounceTime(150)
.distinctUntilChanged()
.subscribe(() => {
if (!this.dataSource) {
return;
}
this.dataSource.filter = this.filter.nativeElement.value;
});
}
}


export class ExampleDataSource extends DataSource<Baza> {
_filterChange = new BehaviorSubject('');

get filter(): string {
return this._filterChange.value;
}

set filter(filter: string) {
this._filterChange.next(filter);
}

filteredData: Baza[] = [];
renderedData: Baza[] = [];

constructor(private _exampleDatabase: DataService,
private _paginator: MatPaginator,
private _sort: MatSort) {
super();
// Reset to the first page when the user changes the filter.
this._filterChange.subscribe(() => this._paginator.pageIndex = 0);
}

/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<Baza[]> {
// Listen for any changes in the base data, sorting, filtering, or pagination
const displayDataChanges = [
this._exampleDatabase.dataChange,
this._sort.sortChange,
this._filterChange,
this._paginator.page,
];

this._exampleDatabase.getAllItems();

return Observable.merge(...displayDataChanges).map(() => {
// Filter data
this.filteredData = this._exampleDatabase.data.slice().filter((item: Baza) => {
const searchStr = (item.ident + item.naziv + item.mt + item.lokacija + item.napomena).toLowerCase();
return searchStr.indexOf(this.filter.toLowerCase()) !== -1;
});

// Sort filtered data
const sortedData = this.sortData(this.filteredData.slice());

// Grab the page's slice of the filtered sorted data.
const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
this.renderedData = sortedData.splice(startIndex, this._paginator.pageSize);
return this.renderedData;
});
}

disconnect() {
}

/** Returns a sorted copy of the database data. */
sortData(data: Baza[]): Baza[] {
... sort stuff
}

这是我想我应该进行字段更新的 DataService:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import { Baza } from '../models/kanban.baza';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {
private readonly API_URL = 'http://localhost/api/'

/** Stream that emits whenever the data has been modified. */
dataChange: BehaviorSubject<Baza[]> = new BehaviorSubject<Baza[]>([]);

constructor(private httpClient: HttpClient) {
}

get data(): Baza[] {
return this.dataChange.value;
}

getAllItems(): void {
this.httpClient.get<Baza[]>(this.API_URL).subscribe(data => {
this.dataChange.next(data['items']);
});
}

addItem(baza: Baza): void {
this.httpClient.post(this.API_URL, Baza).subscribe(data => {
//THIS WAS MY BEST TRY BUT IT DOESN'T WORK :(
const copiedData = this.data.slice();
copiedData.push(baza);
console.log(copiedData);
this.dataChange.next(copiedData);
});
}


updateItem(baza: Baza): void {
this.httpClient.put(this.API_URL + baza.id, baza).subscribe();
}

deleteItem(id: number): void {
this.httpClient.delete(this.API_URL + id, {headers: new HttpHeaders().set('Access-Control-Allow-Origin', '*')} ).subscribe();
}
}

2017 年 11 月 27 日更新:

好的,我终于想出了如何触发新行添加。我不得不在表组件中调用 dataChange.value。一旦你用一些数据加载它,新行就会立即出现。

const data = {id: 208, ident: 233, naziv: 'test', mt: 291, komada: 2, jm: 'a', orginal: 100, lokacija: 3, napomena: 'pls work'};
this.exampleDatabase.dataChange.value.push(data);

DataService 中的相同内容将不起作用:

this.dataChange.value.push(data); 

Plunker 在这里:

https://plnkr.co/edit/IWCVsBRl54F7ylGNIJJ3?p=info

编辑 28.11.2017:

现在唯一剩下的就是构建添加、编辑和删除的逻辑。因为添加很容易,它只是“value.push(data)”。感谢大家的帮助。

最佳答案

花了我一些时间,但我终于让一切正常。您的回答和不同的方法也有帮助。所以,如果有人遇到麻烦,这是我的 CRUD 实现:

https://github.com/marinantonio/angular-mat-table-crud

截图: Alt Text

或者您可以查看项目演示: https://marinantonio.github.io/angular-mat-table-crud/

关键部分在table.ts文件中:

....
addNew(issue: Issue) {
const dialogRef = this.dialog.open(AddDialogComponent, {
data: {issue: issue }
});

dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
this.exampleDatabase.dataChange.value.push(this.dataService.getDialogData());
this.refreshTable();
}
});
}

startEdit(i: number, id: number, title: string, state: string, url: string, created_at: string, updated_at: string) {
this.index = i;
this.id2 = id;
console.log(this.index);
const dialogRef = this.dialog.open(EditDialogComponent, {
data: {id: id, title: title, state: state, url: url, created_at: created_at, updated_at: updated_at}
});

dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
// Part where we do frontend update, first you need to find record using id
const foundIndex = this.exampleDatabase.dataChange.value.findIndex(x => x.id === this.id2);
// Then you update that record using dialogData
this.exampleDatabase.dataChange.value[foundIndex] = this.dataService.getDialogData();
// And lastly refresh table
this.refreshTable();
}
});
}

deleteItem(i: number, id: number, title: string, state: string, url: string) {
this.index = i;
this.id2 = id;
const dialogRef = this.dialog.open(DeleteDialogComponent, {
data: {id: id, title: title, state: state, url: url}
});

dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
const foundIndex = this.exampleDatabase.dataChange.value.findIndex(x => x.id === this.id2);
this.exampleDatabase.dataChange.value.splice(foundIndex, 1);
this.refreshTable();
}
});
}


private refreshTable() {
// If there's no data in filter we do update using pagination, next page or previous page
if (this.dataSource._filterChange.getValue() === '') {
if (this.dataSource._paginator.pageIndex === 0) {
this.dataSource._paginator.nextPage();
this.dataSource._paginator.previousPage();
} else {
this.dataSource._paginator.previousPage();
this.dataSource._paginator.nextPage();
}
// If there's something in filter, we reset it to 0 and then put back old value
} else {
this.dataSource.filter = '';
this.dataSource.filter = this.filter.nativeElement.value;
}
}
....

关于Angular - Material 表,是否可以在不刷新整个表的情况下更新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com