在用户提交反应性表单并使用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方法中。数据不更新。控制台日志显示相同的数据,但是如果手动刷新页面,则会得到数据。
发布后从GET api调用中刷新数据的正确/最佳方法是什么?
发布于 2018-06-19 02:31:18
从您编写的内容来看,您的getAllProjects方法在完成storePage之前被调用,因为这些调用本质上是异步的,因此一旦您的storePage完成了它的订阅,就必须调用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);
this.getAllProjects();
}
);
console.log(this.pages);
}https://stackoverflow.com/questions/50919775
复制相似问题