【问题标题】:Angular 2 reload data on PostAngular 2 在 Post 上重新加载数据
【发布时间】:2018-06-19 14:44:26
【问题描述】:

我想在用户提交响应式表单并使用 api 发布到服务器后从服务器刷新我的数据数组。

我已经看到了两种实现这一点的方法。

方法一 - 刷新间隔。

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() 到提交方法。数据不更新。控制台日志显示相同的数据,但是如果我手动刷新页面,我会得到数据。

在 POST 之后从 GET api 调用刷新数据的正确/最佳方法是什么?

【问题讨论】:

  • 当您调用 storePage 时,this.getAllProjects(); 应该在里面,因为这些调用本质上是异步的。

标签: angular typescript


【解决方案1】:

根据您所写的内容,您的 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);
}

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多