如何在发出 HttpRequest 后立即更新 Angular 中的组件?

How do I update component in Angular instantly after the HttpRequest is made?

我有一项服务可以从服务器获取 "posts",然后显示在我应用程序的 "home" 组件上。我在主页组件上也有一个表单,可以删除 posts。我想在创建新的 post 后(使用表单)或删除 post 后立即更新组件。目前 Post/Delete 确实有效,但我必须刷新页面才能显示更改。

我在 post/delete 之后尝试了 "GET",但仍然无效。我假设在执行 GET 代码行之前,数据没有时间成为 deleted/posted。我还尝试创建一个拦截器并拦截每个 HTTP 请求,但这似乎也不起作用。关于我应该研究什么的任何建议。我对 Angular(以及一般的 Web 开发)相当陌生。

[api.service.ts]

        @Injectable({
        providedIn: "root"
        })

        getHomeNotifications(): Observable<HomeComponent[]> {
        return this.http.get<HomeComponent[]>(
        this.api + "/notification/list/active"
        );
        }

        removeNotification(Notifications): Observable<HomeComponent> {
        return this.http.post<HomeComponent>(
        this.api + "/notification/expire",
        Notifications
        );
        }

        postNotifications(form: HomeComponent): Observable<HomeComponent> {
        return this.http.post<HomeComponent>(
        this.api + "/notification/create",
        form
        );
        }

[拦截器]

        intercept(req: HttpRequest<any>, next: HttpHandler): 
        Observable<HttpEvent<any>> {
        return next.handle(req).pipe(finalize(()=>
        this.apiService.getCurrentNotifications()
        }

[home.component.ts]

        getCurrentNotifications(): void {
        this.apiService.getHomeNotifications().subscribe(data => {
        this.notifications = data;
        });
        }

        onRemove(id) {
          this.noti = new Notifications();
          this.noti.notificationId = id;
          this.apiService.removeNotification(this.noti).subscribe();
        });


        onPost(): void {
          this.apiService.postNotifications(this.pushForm.value).subscribe();
        }

我的第一次尝试只是尝试 运行 在 this.apiService.removeNotification(this.noti).subscribe(); 之后的 getCurrentNotifications();等等,但这没有用。我的第二次尝试是 运行 设置拦截器,但也没有成功。

所以这花了我一整天的时间,但我终于修好了。在订阅中写入 () => function 将在订阅完成后触发该功能。所以在我的 onRemove 和 onPost 中:

 onPost(): void {
          this.apiService.postNotifications(this.pushForm.value).subscribe(() => this.getCurrentNotification());
        }

我正在调用更新函数来加载我的 getCurrentNotification 以重新加载组件并获取最新数据。这适用于 post,但我没有删除。我认为这是订阅功能的问题。我花了几个小时才意识到这是一个 back-end 问题。后端发生的事情是,由于通知正在通过过期请求,"Valid to" 日期立即更改为今天 date-hour-second-ms。所以有时候,这种情况发生得太快以至于请求在时间更改之前就完成了——这会导致通知不会过期(当然直到我重新加载页面)。因此更改 back-end 以便将过期通知有效时间更改为当前时间 - 1 分钟解决了该问题。希望这能帮助遇到同样问题的人 :)