首页 > 解决方案 > 角度保存编辑的内容

问题描述

我正在编写一个代码,用户可以在其中更改屏幕上的段落并保存它。目前,用户可以更改段落并且save()操作正常。但是保存后,更改的段落不会通过网络。该段落不会更改,它会保存未经编辑的版本,就好像我什么都没写一样。我应该改变什么来实现这一目标?

HTML:

  <div class="content fuse-white ml-24 mr-8 h-100-p" fusePerfectScrollbar>
            <div class="label-list">
                <p>
                    A Paragraph: 
    
                    <span contenteditable="true">
                        {{_stickerData?.StickerData}}
                    </span>
                </p>
              
            </div>
        </div>

TS:

save(){
    this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
        disableClose: false,
    });
    
    this.confirmDialogRef.componentInstance.confirmMessage =
    "The paragraph will be changed";

this.confirmDialogRef.afterClosed().subscribe((result) => {
    if (result) {
        this._productionService
            .saveStickerData(this._stickerData)
            .subscribe((response: IStickerData) => {
                this._stickerData = response;
                this._messages.Show(            
                    "SUCCESS",
                    3
                );
            });
    }
});
}

服务TS:

saveStickerData(data: IStickerData): Observable<IStickerData> {
        return this._http.post("Production/SaveStickerData", data);
    }

标签: javascripthtmlangulartypescript

解决方案


[已编辑] 当您在模板中插入变量并使用 contenteditable - 它不会更新您的变量。您应该手动更新它。

<span contenteditable [textContent]="_stickerData?.StickerData" (input)="onStickerDataChange($event.target.innerHTML)">
</span>

在 TS 中应该是这样的:

onStickerDataUpdate(data) {
    this._stickerData.StickerData = data;
}

有用的链接:1 , 2 [旧建议]

  1. 您确定回复已编辑段落吗?如果是,则更改检测可能存在问题。在组件构造函数中导入 ChangeDetectorRef 并在获取数据时触发 markForCheck() 方法。
  2. 嵌套订阅是一种不好的做法,请尝试使用 switchMap() 进行重构

这是一个伪代码来展示这个想法:

   class MyComponent {
      constructor(private cd: ChangeDetectorRef) {}
        
       save(){
         this.confirmDialogRef = 
         this._dialog.open(FuseConfirmDialogComponent, {
            disableClose: false,});
         this.confirmDialogRef.componentInstance.confirmMessage =
    "The paragraph will be changed";

         this.confirmDialogRef.afterClosed().pipe(switchMap(result) => {
           if (result) {
             return this._productionService.saveStickerData(this._stickerData);
           } else {
             return EMPTY;
           }
        }).subscribe((response) => {
          this._stickerData = response;
          this._messages.Show(            
             "SUCCESS",
             3
          );
          this.cd.markForCheck();
        });
      }
   }

推荐阅读