首页 > 解决方案 > 需要帮助在角度 PUT 函数后执行 GET

问题描述

我创建了一个角度弹出窗口,可以编辑具有名称和图像属性的主题并更新(PUT)到服务器。

保存后,我的组件将根据弹出窗口返回GET的主题显示在视图中。Id这里的PUT方法运行速度比 慢GET,导致我的视​​图无法更新,因为它GET是旧主题,而不是更新的主题。

当我关闭对话框时调用该PUT函数。关闭后,我订阅以获取主题结果,并运行该GET功能。

topic.component.tseditTopic()当我单击编辑按钮时调用方法,将所选主题传递给对话框数据然后弹出。关闭后,我得到结果(这是更新的主题)和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.tsonSave当我单击保存时运行,将图像文件和主题名称发布到服务器并返回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会运行。但似乎它们两者同时运行(?)并且在需要更新图像文件时速度较慢。不知道怎么解决,希望大家看看。PUTsubscribe()PUT

标签: angularhttprequestput

解决方案


我认为你的问题来自于线路

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。


推荐阅读