【发布时间】:2024-01-09 22:51:01
【问题描述】:
我有一项服务从服务器获取“帖子”,然后显示在我的应用程序的“主页”组件上。我在 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()等,但没有奏效。我的第二次尝试是运行拦截器,但也没有运气。
【问题讨论】:
标签: angular service components httprequest updating