谁能告诉我我哪里做错了?错误“未定义”?数据更新期间发生错误。
错误TypeError:无法设置未定义的属性“ id” 在AdminComponent.push ../ src / app / admin / admin.component.ts.AdminComponent.onUpdate中 (admin.component.ts:130) 在Object.eval [作为handleEvent](AdminComponent.html:62) 在handleEvent(core.js:10251) 在callWithDebugContext(core.js:11344) 在Object.debugHandleEvent [作为handleEvent](core.js:11047) 在dispatchEvent(core.js:7710) 在core.js:9190 在SafeSubscriber.schedulerFn [作为_next](core.js:3563) 在SafeSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber .__ tryOrUnsub(Subscriber.js:253) 在SafeSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber.next (Subscriber.js:191)
component.ts:
export class AdminComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('input') inputRef: ElementRef
@ViewChild('modal_edit') modal_editRef: ElementRef
users: User[]
userId: string = null
modal_edit: MaterialInstance
form: FormGroup
image: File
imagePreview = ''
user: User
constructor(
private userService: UserService
) { }
ngOnInit() {
this.form = new FormGroup({
username: new FormControl(null, [Validators.required]),
password: new FormControl(null, [Validators.required, Validators.minLength(6)]),
name: new FormControl(null, Validators.required),
roles: new FormControl(null, Validators.required)
})
}
private loadUser() {
this.userService.fetch().subscribe(
users => {
this.users = users
}
);
}
ngAfterViewInit() {
this.modal_edit = MaterialService.initModal(this.modal_editRef)
}
ngOnDestroy() {
this.modal_edit.destroy()
}
onSelectUser(user: User){
this.userId = user.id
this.form.patchValue({
name: user.name,
username: user.username,
roles: user.roles
})
this.imagePreview = user.photoSrc
this.modal_edit.open()
MaterialService.updateTextInputs()
}
onCancel() {
this.modal_edit.close()
this.form.reset(
{
name: '',
username: '',
roles: '',
imagePreview: '',
password: ''
}
)
}
triggerClick() {
this.inputRef.nativeElement.click()
}
onFileUpload(event: any) {
const file = event.target.files[0]
this.image = file
const reader = new FileReader()
reader.onload = () => {
this.imagePreview = reader.result
}
reader.readAsDataURL(file)
}
onUpdate() {
if(this.userId) {
this.user.id = this.userId
this.userService.update(this.user.id, this.form.value.name, this.form.value.username, this.form.value.password, this.form.value.roles, this.image).subscribe(
() => {
MaterialService.toast('Changes saved')
this.loadUser()
},
error => {
this.form.enable()
MaterialService.toast(error.error.message)
},
() => {
this.modal_edit.close()
})
}
}
}
服务:
update(id: string, name: string, username: string, password: string, roles?: string, image?: File): Observable<User> {
const fd = new FormData()
if (image) {
fd.append('image', image, image.name)
}
fd.append('name', name)
fd.append('username', username)
fd.append('password', password)
fd.append('roles', roles)
return this.http.patch<User>(`/api/admin/${id}`, fd)
}