首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度2在桩上重新加载数据

角度2在桩上重新加载数据
EN

Stack Overflow用户
提问于 2018-06-19 02:19:08
回答 1查看 2K关注 0票数 2

在用户提交反应性表单并使用api向服务器发布后,我希望刷新来自服务器的数据数组。

我见过两种方法来达到这个目的。

方法1 -刷新间隔.

app.component

代码语言:javascript
复制
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

代码语言:javascript
复制
getProjects() {
    return this.http.get("/api/project/getallprojects");
}

storePage(project: Project) {
    return this.http.post('/api/Project/postproject', project);
}

这在功能上适用于我,但是我不需要每隔x秒刷新一次。对我的需求来说,这似乎没有效率。

方法2-使用如下内容:

代码语言:javascript
复制
this.projects.push(project);

这对我不起作用,因为数据需要包括分配给数据库分配给每个对象的id。因此,我需要调用服务器并重新获取数据。

即使方法1在功能上可以工作,但以下内容(this.getAllProjects())却不起作用:

代码语言:javascript
复制
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调用中刷新数据的正确/最佳方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-19 02:31:18

从您编写的内容来看,您的getAllProjects方法在完成storePage之前被调用,因为这些调用本质上是异步的,因此一旦您的storePage完成了它的订阅,就必须调用getAllProjects

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50919775

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档