首页 > 解决方案 > 适应 Angular 8 中 Reactive Form PatchValue 中的最终 NULL 值

问题描述

我有一个表格,可以在更新时从中删除图像。我在 Angular 8 中使用 Reactive Forms。我使用 PatchValue 显示来自 API 的现有数据,如下所示:

editArticle(article: Article) {
    this.articleEdit.patchValue(
      {
        feed_type: article.feed_type.data.id,
        title: article.title,
        sub_title: article.sub_title,
        description: article.description,
        text_content: article.text_content,
        author_name: article.author_name,
        author_avatar: article.author_avatar.data,
        video_url: article.video_url,
        header_image: article.header_image.data,<-- this is the issue BTW
        featured_image: article.featured_image.data,
        twitter: article.twitter,
        facebook: article.facebook,
        instagram: article.instagram,
        advertising_banner: article.advertising_banner.data,
        ad_link: article.ad_link
      }
    );
  }

当我这样做时(更新代码)

deleteHeaderImage(article: Article) {
this.startLoading();
let updatedArticle = {
  header_image: {
    id: null
  }
}
this.articleService.updateArticleById(this.id, updatedArticle)
  .subscribe(
    response => {
      if (response) {
        this.article = response.data;
        this.articleEdit.patchValue({
          header_image: null
        })
        this.stopLoading();
      }
    }
  )

}

在响应上设置 patchValue 可以消除错误,但是当我刷新页面时,图像消失了,这很好,但是错误在控制台中返回并恢复到 editArticle() 中的原始 patchValue 对象

表单已成功更新并已删除图像,但随后出现以下错误:

ERROR TypeError: Cannot read property 'data' of null

在 response.data 之后

经检查,这与上述 editArticle() 方法中的 patchValue 正在寻找article.header_image.data的事实有关

我一直认为这与 .html 文件有关,并确保有安全措施来检查是否返回 null 值,但似乎与上述有关。我不知道该怎么办。过去有人解决过这个问题吗?我有点卡住了。

标签: angularangular-reactive-formspatch

解决方案


推荐阅读