angular - 如何在发出 HttpRequest 后立即更新 Angular 中的组件?
问题描述
我有一项服务从服务器获取“帖子”,然后显示在我的应用程序的“主页”组件上。我在 home 组件上也有一个表单,可以删除帖子。我想在发布新帖子(使用表单)或删除帖子后立即更新组件。目前发布/删除确实有效,但我必须刷新页面才能显示更改。
我在发布/删除后尝试了“GET”,但它仍然不起作用。我假设在执行 GET 代码行之前没有时间删除/发布数据。我还尝试创建一个拦截器并拦截每个 HTTP 请求,但这似乎也不起作用。关于我应该研究什么的任何建议。我对 Angular(以及一般的网络开发)相当陌生。
[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 以重新加载组件并获取最新数据。这适用于发布,但我没有删除。我认为这是订阅功能的问题。我花了几个小时才意识到这是一个后端问题。后端发生的情况是,由于通知正在通过过期请求,“有效期至”日期立即更改为今天的日期-小时-秒-毫秒。所以有时,这种情况发生得太快,以至于请求在时间改变之前就完成了——这会导致通知不会过期(当然,直到我重新加载页面)。因此更改后端,使过期通知有效时间更改为当前时间 - 1 分钟解决了该问题。希望这可以帮助人们解决同样的问题:)
推荐阅读
- python - 抓取的网站数据未写入 CSV
- python - 从表格数据中提取列
- windows - 拒绝访问路径“C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\Windows\INetCache\Content.IE5”
- c - 使用 fork 转换为大写的 C 程序
- java - 以编程方式将引号添加到 EditText
- php - 如何在laravel 5.5中使用php的flock()函数
- python - 我想在产品有折扣价时显示折扣价
- python - 使用 QAbstractTableModel 在 pyqts QTableView 中插入和删除行
- python - 使用窗口和层次逻辑使用 Pandas 创建计算列
- azure - Azure ADDS 的域控制器策略