我想在用户提交被动表单后从服务器刷新我的数据数组,并使用api发布到服务器。
我已经看到了实现这一目标的两种方法。
方法1 - 刷新间隔。
app.component
ngOnInit(): void {
this.getAllProjects();
this.interval = setInterval(() => {
this.getAllProjects();
}, 3000);
}
getAllProjects() {
this.dataService.getProjects().subscribe(
data => { this.pages = data },
err => console.error(err),
() => console.log(this.pages)
);
}
onSubmitProject() {
this.newProject.CourseId = this.addProjectForm.value.CourseId;
this.newProject.TypeId = this.addProjectForm.value.TypeId;
this.newProject.SignOff = this.addProjectForm.value.SignOff;
this.newProject.StartDateTime = this.addProjectForm.value.StartDateTime;
this.dataService.storePage(this.newProject)
.subscribe(
(response) => console.log(response),
(error) => console.log(error)
);
}
dataService.ts
getProjects() {
return this.http.get("/api/project/getallprojects");
}
storePage(project: Project) {
return this.http.post('/api/Project/postproject', project);
}
这个功能对我有用,但是我不需要每隔x秒刷新一次。这似乎对我的需求效率低下。
方法2 - 使用类似:
this.projects.push(project);
这对我不起作用,因为数据需要包含分配给数据库分配的每个对象的id。因此,我需要调用服务器并重新获取数据。
即使方法1在功能上有效,但以下(this.getAllProjects())不会:
onSubmitProject() {
this.newProject.CourseId = this.addProjectForm.value.CourseId;
this.newProject.TypeId = this.addProjectForm.value.TypeId;
this.newProject.SignOff = this.addProjectForm.value.SignOff;
this.newProject.StartDateTime = this.addProjectForm.value.StartDateTime;
this.dataService.storePage(this.newProject)
.subscribe(
(response) => console.log(response),
(error) => console.log(error)
);
this.getAllProjects();
console.log(this.pages);
}
如果我从方法1中删除刷新间隔,我添加this.getAllProjects();和console.log()到submit方法。数据不会更新。控制台日志显示相同的数据,但如果我手动刷新页面,我会得到数据。
POST后,从GET api调用刷新数据的正确/最佳方法是什么?
答案 0 :(得分:2)
根据您所写的内容,在完成getAllProjects
之前调用了storePage
方法,因为这些调用本质上是异步的,您必须在getAllProjects
之后调用storePage
完成在其订阅中。
onSubmitProject() {
this.newProject.CourseId = this.addProjectForm.value.CourseId;
this.newProject.TypeId = this.addProjectForm.value.TypeId;
this.newProject.SignOff = this.addProjectForm.value.SignOff;
this.newProject.StartDateTime = this.addProjectForm.value.StartDateTime;
this.dataService.storePage(this.newProject)
.subscribe(response => {
console.log(response);
this.getAllProjects();
}
);
console.log(this.pages);
}