无法使用数据填充"编辑表单"



我检查了很多帖子,但都没能解决我的问题。我想做的是,当我单击编辑按钮时,会出现一个表单对话框。我想用客户数据填充该表单。我可以获取行的数据,但无法用该数据填充表单。

我有服务、客户、客户和客户列表组件。我在客户组件中创建了表单。我想编辑客户列表组件中的一行,因为我在其中有客户列表。我可以通过customer.service中的populateForm(customer(函数将列表中的一行元素作为对象获取,但我无法将它们放入表单中。

customer.service.ts

@Injectable({
providedIn: 'root'
})
export class CustomerService {
formData  : Customer;
list : Customer[];
readonly rootURL = 'http://localhost:8085/api/auth'
public _refreshNeeded$ = new Subject<void>();
constructor(
private http: HttpClient,
) { }

//PUT Request
getCustomers(): Observable<Array<Customer>> {
return this.http.get<CustomerModelResponse>(this.rootURL + '/customer',
{ headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
.pipe(map(x => x.content), catchError(this.handleError));
}
//Refresh after a successful POST Request
get refreshNeeded$() {
return this._refreshNeeded$;
}
//Insert Customer with POST Request
postCustomer(formData: Customer) {
return this.http
.post(this.rootURL + '/customer', formData)
.pipe(
tap(()=>{
this._refreshNeeded$.next();
})
);  
}
//PUT Request
updateCustomer(formData : Customer){
return this.http.put(this.rootURL+'/customer/'+formData.id, formData);   
}
//DELETE Request

deleteCustomer(id : number){
return this.http.delete<CustomerModelResponse>(this.rootURL+'/customer/'+id, 
{headers : new HttpHeaders({'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT,DELETE',
'Access-Control-Allow-Credentials': 'true','Content-Type':'application/json', 
'Authorization': '*',
'Access-Control-Allow-Headers': 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'})})
.pipe(map(x => x.content), catchError(this.handleError));
}
//Handle Error (is not elaborated!!!)
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
//client error
console.log('client error: ' + error.error.message)
} else {
//backend error
console.log(`backend error: ${error.status} error: ${error.error}`)
}
return throwError('Hata oluştu')
}
//Trying to populate form for Edit button
/*populateForm(customer) {
this.formData = Object.assign({}, customer); 
console.log('Row clicked: ', customer); "test" not really part of function, works correctly!
}*/

customer.组件.ts

export class CustomerComponent implements OnInit {

constructor(
private service: CustomerService,
private notificationService: NotificationService,
public formBuilder: FormBuilder,
private ngZone: NgZone,
private router: Router,
public dialogRef: MatDialogRef<CustomerComponent>
) { }
customerForm: FormGroup;
ngOnInit() {
this.submitCustomerForm()
}
submitCustomerForm() {
this.customerForm = this.formBuilder.group({
id: new FormControl(null),
firstname: new FormControl('', Validators.required),
lastname: new FormControl('', Validators.required),
email: new FormControl('', Validators.email),
customerId: new FormControl(null, [Validators.required, Validators.minLength(5)])
});
}
//Creating new form after refreshing list 
initializedFormGroup() {
this.customerForm.setValue({
id: null,
firstname: '',
lastname: '',
email: '',
customerId: null
})
}
onClear() {
this.customerForm.reset();
this.initializedFormGroup();
}

onSubmit() {
if (this.customerForm.valid) {
this.service.postCustomer(this.customerForm.value).subscribe(res => {
this.ngZone.run(() => this.router.navigateByUrl(''))
});
this.customerForm.reset();
this.initializedFormGroup();
this.notificationService.success('İşleminiz tamamlanmıştır')
this.onClose();
}
}
onClose() {
this.customerForm.reset();
this.initializedFormGroup();
this.dialogRef.close();
}
}

customerlist.component.ts

export class CustomerListComponent implements OnInit {
customerData: any = [];
dataSource: MatTableDataSource<Customer>;
@ViewChild(MatPaginator) paginator: MatPaginator;
displayedColumns: string[] = ['firstname', 'lastname', 'email', 'customerId', 'action'];
searchKey: string;
constructor(
private dialog: MatDialog,
public service: CustomerService,
) {
this.service._refreshNeeded$.subscribe(() => {
this.service.getCustomers().subscribe(data => {
this.customerData = data;
this.dataSource = new MatTableDataSource<Customer>(this.customerData);
setTimeout(() => {
this.dataSource.paginator = this.paginator;
}, 0);
})
})
this.service.getCustomers().subscribe(data => {
this.customerData = data;
this.dataSource = new MatTableDataSource<Customer>(this.customerData);
setTimeout(() => {
this.dataSource.paginator = this.paginator;
}, 0);
})
}

ngOnInit() { }
deleteCustomer(index: number, e) {
if (window.confirm('Are you sure?')) {

const data = this.dataSource.data;
data.splice((this.paginator.pageIndex * this.paginator.pageSize) + index, 1);
this.dataSource.data = data;
this.service.deleteCustomer(e.id).subscribe()
}
}

onSearchClear() {
this.searchKey = "";
this.applyFilter();
}
applyFilter() {
this.dataSource.filter = this.searchKey.trim().toLowerCase();
}

onEdit(element){
const dialogConfig = new MatDialogConfig();
this.service.populateForm(element);
dialogConfig.autoFocus = true;
dialogConfig.width = "30%";
this.dialog.open(CustomerComponent, dialogConfig);
}
}

customerlist.html编辑按钮部分

<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> </th>
<td mat-cell *matCellDef="let element; let i = index;">
<button mat-icon-button color="primary"(click)="onEdit(element)">
<mat-icon>edit</mat-icon>
</button>
</td>
</ng-container>

您可以将data设置为dialogConfig,而不是在服务上调用方法(您也可以使用服务,但需要使用BehaviorSubject(

客户列表.组件.ts

onEdit(element) {
const dialogConfig = new MatDialogConfig();
// this.service.populateForm(element);
dialogConfig.autoFocus = true;
dialogConfig.width = "30%";
dialogConfig.data = element;
this.dialog.open(CustomerComponent, dialogConfig);
}
// or
onEdit(element) {
const dialogConfig = new MatDialogConfig();
// this.service.populateForm(element);
this.dialog.open(CustomerComponent, {
autoFocus : true,
data : element,
width : "30%",
});
}

customer.component.ts并且在客户组件中,您需要注入如下所示的对话框数据

export class CustomerComponent {
...
constructor(
...,
@Inject(MAT_DIALOG_DATA) public data: DialogData, // `data` will contains the customer data and you can use it to `set` or `patch` the form
...
) {}
...
}

最新更新