这是我的更新组件:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-update-person',
templateUrl: './update-person.component.html',
styleUrls: ['./update-person.component.css']
})
export class UpdatePersonComponent implements OnInit {
id: number;
data: object = {};
// person = []; //ERROR TypeError: Cannot read property 'length' of undefined
// person = any; //ERROR Error: Uncaught (in promise): ReferenceError: any is not defined
person: any; //ERROR TypeError: Cannot read property 'length' of undefined
exist = false;
personObj: object = {};
private headers = new Headers({ 'Content-Type': 'application/json' });
constructor(
private router: Router,
private route: ActivatedRoute,
private http: HttpClient
) {}
confirmationString: string = 'Person updated successfully !!';
isUpdated: boolean = false;
updatePerson = function(person) {
this.personObj = {
p_id: person.p_id,
p_username: person.p_username,
p_image: person.p_image
};
const url = `${'http://localhost:5555/person'}/${this.id}`;
this.http
.put(url, JSON.stringify(this.personObj), { headers: this.headers })
.toPromise()
.then(() => {
this.router.navigate(['/']);
});
};
ngOnInit() {
this.route.params.subscribe(params => {
this.id = +params['id'];
});
this.http
.get('http://localhost:5555/person')
.subscribe((res: Response) => {
this.isUpdated = true;
this.person = res;
for (var i = 0; i < this.person.length; i++) {
if (parseInt(this.person[i].id) === this.id) {
this.exist = true;
this.data = this.person[i];
break;
} else {
this.exist = false;
}
}
});
}
}
这可以正常工作而不会引发任何错误。但是,单击更新按钮后,空白数据将保存到我的 json 服务器。
认为问题出在person: any;
. 你可以看到我用那个 person 变量尝试过的其他一些事情以及我得到的相应错误。