angular - 需要帮助在角度 PUT 函数后执行 GET
问题描述
我创建了一个角度弹出窗口,可以编辑具有名称和图像属性的主题并更新(PUT)到服务器。
保存后,我的组件将根据弹出窗口返回GET
的主题显示在视图中。Id
这里的PUT
方法运行速度比 慢GET
,导致我的视图无法更新,因为它GET
是旧主题,而不是更新的主题。
当我关闭对话框时调用该PUT
函数。关闭后,我订阅以获取主题结果,并运行该GET
功能。
topic.component.ts
,editTopic()
当我单击编辑按钮时调用方法,将所选主题传递给对话框数据然后弹出。关闭后,我得到结果(这是更新的主题)和GET
服务器中的主题再次带有主题 ID。
private openEditDialog(topic: Topic) {
let dialogConfig = new MatDialogConfig();
dialogConfig.panelClass = 'edit-dialog-component';
dialogConfig.width = '1027px';
dialogConfig.height = '491.12px';
dialogConfig.position = {top: '138px'};
dialogConfig.data = topic;
return dialogConfig;
}
public editTopic(topic: Topic): void {
const dialogRef = this.matDialog.open(EditDialogComponent, this.openEditDialog(topic));
dialogRef.afterClosed().subscribe(
(res: any) => {
if (res) {
this.getTopicById(res.get('id').value);
}
},
(err) => console.error(err)
);
}
edit-dialog.component.ts
,onSave
当我单击保存时运行,将图像文件和主题名称发布到服务器并返回FormGroup
值以显示在视图上
public onSave(): void {
const formData = new FormData();
let topic = {
id: this.topicForm.get('id').value,
name: this.topicForm.get('title').value
};
formData.append('newsTopic', JSON.stringify(topic));
if (this.file) {
formData.append('file', this.file);
}
console.log(formData);
this.topicService.updateTopicImage(formData)
.subscribe((res) => {
if (res) {
this.topicForm.patchValue({
id: res.id,
title: res.name,
imageURL: res.image
});
}
});
this.dialogRef.close(this.topicForm);
}
updateTopicImage PUT formdata 到服务器
public updateTopicImage(formData) {
return this.httpClient.put<any>(APIurl, formData);
}
由于方法,我希望它GET
会运行。但似乎它们两者同时运行(?)并且在需要更新图像文件时速度较慢。不知道怎么解决,希望大家看看。PUT
subscribe()
PUT
解决方案
我认为你的问题来自于线路
this.dialogRef.close(this.topicForm);
这里的问题是您在服务器上调用 PUT 方法并且在关闭弹出窗口之前不等待服务器的响应。
你能试试这个吗
public onSave(): void {
const formData = new FormData();
let topic = {
id: this.topicForm.get('id').value,
name: this.topicForm.get('title').value
};
formData.append('newsTopic', JSON.stringify(topic));
if (this.file) {
formData.append('file', this.file);
}
console.log(formData);
this.topicService.updateTopicImage(formData)
.subscribe((res) => {
if (res) {
this.topicForm.patchValue({
id: res.id,
title: res.name,
imageURL: res.image
});
// I've put the return inside the response of the PUT call.
this.dialogRef.close(this.topicForm);
}
});
}
编辑
为此更改此方法
public updateTopicImage(formData) {
return this.httpClient.put<any>(APIurl, formData.value);
}
您不能将表单发送到 API,您必须将表单内的对象发送到 API。
推荐阅读
- hibernate - QuerySyntaxException:意外令牌
- r - 包括 save.image (R) 中的参数值
- hive - 如何在 Hive 中执行此操作?
- android - 从中心裁剪位图以适应显示宽度和高度
- java - 渴望获取特定对象的特定惰性属性
- javascript - Angular 7 - 生产模式:我无法使用 tab 键浏览页面
- c++ - 使用 gnu 缩进如何将 int * 转换为 int*
- r - 为什么 type.convert 不将存储为数字的大“整数”转换为整数?
- javascript - 需要动态屏幕尺寸
- entity-framework - 如何使用空间数据使用 EF Core 2.2 进行迁移?