Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 无法用数据填充编辑表单_Angular_Angular Material - Fatal编程技术网

Angular 无法用数据填充编辑表单

Angular 无法用数据填充编辑表单,angular,angular-material,Angular,Angular Material,我检查了很多帖子,但我无法解决我的问题。我想做的是,当我点击编辑按钮时,会出现一个表单对话框。我想用客户数据填充该表单。我可以获取行的数据,但无法用该数据填充表单 我有服务、客户、客户和客户列表组件。我在customer组件中创建了表单。我想编辑客户列表组件中的一行,因为我在其中有客户列表。我可以通过customer.service中的populateForm(customer)函数将列表行中的元素作为对象获取,但我无法将它们放入表单中 客户服务 @Injectable({ provided

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

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

客户服务

@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!
  }*/

@可注入({
providedIn:'根'
})
导出类CustomerService{
formData:客户;
名单:客户[];
只读根URL=http://localhost:8085/api/auth'
public _$=新主题();
建造师(
私有http:HttpClient,
) { }
//提出请求
getCustomers():可观察{
返回this.http.get(this.rootURL+'/customer',
{headers:new-HttpHeaders({'Content-Type':'application/json'})})
.pipe(map(x=>x.content),catchError(this.handleError));
}
//成功的POST请求后刷新
获取所需的刷新$(){
退回这个。_$;
}
//插入带有POST请求的客户
邮政客户(formData:Customer){
返回此文件。http
.post(this.rootURL+/customer',formData)
.烟斗(
点击(()=>{
此._.next();
})
);  
}
//提出请求
updateCustomer(formData:Customer){
返回this.http.put(this.rootURL+'/customer/'+formData.id,formData);
}
//删除请求
删除客户(id:编号){
返回此.http.delete(此.rootURL+'/customer/'+id,
{headers:newhttpheaders({'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'GET,HEAD,OPTIONS,POST,PUT,DELETE',
“访问控制允许凭据”:“true”,“内容类型”:“应用程序/json”,
“授权”:“*”,
“访问控制允许标头”:“访问控制允许标头、来源、接受、X-Requested-With、内容类型、访问控制请求方法、访问控制请求标头”})
.pipe(map(x=>x.content),catchError(this.handleError));
}
//句柄错误(未详细说明!!!)
私有句柄错误(错误:HttpErrorResponse){
if(error.error instanceof ErrorEvent){
//客户端错误
console.log('client error:'+error.error.message)
}否则{
//后端错误
log(`backend error:${error.status}error:${error.error}`)
}
回击投手(“Hata oluştu”)
}
//尝试为“编辑”按钮填充表单
/*大众形式(客户){
this.formData=Object.assign({},customer);
log('Row clicked:',customer);“test”实际上不是函数的一部分,工作正常!
}*/
customer.component.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();
  }

}
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);
  }
}
导出类CustomerComponent实现OnInit{
建造师(
私人服务:客户服务,
私人通知服务:通知服务,
公共formBuilder:formBuilder,
私人ngZone:ngZone,
专用路由器:路由器,
公共dialogRef:MatDialogRef
) { }
customerForm:FormGroup;
恩戈尼尼特(){
this.submitCustomerForm()
}
submitCustomerForm(){
this.customerForm=this.formBuilder.group({
id:new FormControl(空),
名字:新FormControl(“”,需要验证程序),
lastname:new FormControl(“”,需要验证程序),
电子邮件:新FormControl(“”,Validators.email),
customerId:new FormControl(null,[Validators.required,Validators.minLength(5)])
});
}
//刷新列表后创建新表单
initializedFormGroup(){
此参数为.customerForm.setValue({
id:null,
名字:'',
姓氏:“”,
电子邮件:“”,
customerId:null
})
}
onClear(){
此参数为.customerForm.reset();
this.initializedFormGroup();
}
onSubmit(){
如果(此.customerForm.valid){
this.service.postCustomer(this.customerForm.value).subscribe(res=>{
this.ngZone.run(()=>this.router.navigateByUrl(“”))
});
此参数为.customerForm.reset();
this.initializedFormGroup();
这是一个成功的通知服务
这个。onClose();
}
}
onClose(){
此参数为.customerForm.reset();
this.initializedFormGroup();
this.dialogRef.close();
}
}
customer-list.component.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();
  }

}
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);
  }
}
导出类CustomerListComponent实现OnInit{
customerData:any=[];
数据源:MatTableDataSource;
@ViewChild(MatPaginator)分页器:MatPaginator;
displayedColumns:string[]=['firstname','lastname','email','customerId','action'];
搜索键:字符串;
建造师(
私人对话:MatDialog,
公共服务:客户服务,
) {
此.service.\u.subscribe(()=>{
this.service.getCustomers().subscribe(数据=>{
this.customerData=数据;
this.dataSource=新MatTableDataSource(this.customerData);
设置超时(()=>{
this.dataSource.paginator=this.paginator;
}, 0);
})
})
this.service.getCustomers().subscribe(数据=>{
this.customerData=数据;
this.dataSource=新MatTableDataSource(this.customerData);
设置超时(()=>{
this.dataSource.paginator=this.paginator;
}, 0);
})
}
ngOnInit(){}
删除客户(索引:编号,e){
if(window.confirm('you sure?')){
const data=this.dataSource.data;
拼接数据((this.paginator.pageIndex*this.paginator.pageSize)+索引,1);
this.dataSource.data=数据;
this.service.deleteCustomer(e.id).subscribe()
}
}
onSearchClear(){
this.searchKey=“”;
this.applyFilter();
}
applyFilter(){
this.dataSource.filter=this.searchKey.trim().to
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
    ...
  ) {}

  ...

}