我有一个对象列表。用户可以单击一个,然后加载一个子组件以编辑该组件。

我的问题是,当用户返回到列表组件时,子组件必须在ngOnDestroy方法中进行一些清理-这需要调用服务器以对对象进行最终的“修补”。有时,此处理可能会有点慢。

当然,发生的情况是用户返回列表,并且api调用在ngOnDestroy的数据库事务完成之前完成了,因此用户看到了过时的数据。

  ngOnDestroy(){
    this.destroy$.next();
    this.template.template_items.forEach((item, index) => {
      // mark uncompleted items for deletion
      if (!item.is_completed) {
        this.template.template_items[index]['_destroy'] = true;
      };
    });
    // NOTE
    // We don't care about result, this is a 'silent' save to remove empty items,
    // but also to ensure the final sorted order is saved to the server
    this._templateService.patchTemplate(this.template).subscribe();
    this._templateService.selectedTemplate = null;
  }

我了解不建议您进行同步调用,因为它会阻塞UI /整个浏览器,这不是很好。

我敢肯定有多种方法可以解决这个问题,但是真的不知道哪种方法最好(特别是因为Angular不支持同步请求,所以我不得不依靠标准的ajax来做到这一点)。

我确实想到的一个想法是ngOnDestroy可以将“标记”传递给API,然后可以将该对象标记为“处理中”。当列表组件进行调用时,它可以检查每个对象是否具有该标记,并为处于该状态的任何对象显示“刷新陈旧数据”按钮(无论如何,有99%的时间只有一个,用户编辑的最新版本)。与仅将异步调用更改为同步调用相比,似乎有点废话解决方案,并且需要大量额外的代码。

其他人肯定也遇到过类似的问题,但是除了this sync one之外,我似乎找不到任何明确的示例。

编辑

请注意,此子组件已具有CanDeactive防护。它要求用户确认(即放弃更改)。因此,如果他们单击以确认,则将执行ngOnDestroy中的此清理代码。但是请注意,这不是用户真正“放弃”更改的典型 Angular 形式。基本上,在离开此页面之前,服务器必须对最终数据集进行一些处理。因此,理想情况下,我不希望用户在ngOnDestroy完成之前就离开-如何强制其等待该api调用完成?

我的CanDeactive守护程序的实现与Hero应用程序的official docs几乎相同,并连接到通用对话框服务中,该服务提示用户是希望保留在页面上还是继续前进。这里是:
  canDeactivate(): Observable<boolean> | boolean {
    console.log('deactivating');
    if (this.template.template_items.filter((obj) => { return !obj.is_completed}).length < 2)
      return true;

    // Otherwise ask the user with the dialog service and return its
    // observable which resolves to true or false when the user decides
    return this._dialogService.confirm('You have some empty items. Is it OK if I delete them?');
  }

但是,文档并未明确说明我的情况-即使我将清除代码从ngOnDestroy移至对话框的“YES”方法处理程序,它仍必须调用api,因此YES处理程序仍将在API之前完成做到了,我又遇到了同样的问题。

更新

阅读所有评论后,我猜想解决方案是这样的。更改防护:
    return this._dialogService.confirm('You have some empty items.
        Is it OK if I delete them?');


    return this._dialogService.confirm('You have some empty items.
        Is it OK if I delete them?').subscribe(result => {
      ...if yes then call my api and return true...
      ...if no return false...
      });

最佳答案

如您所说,方法有很多,它们取决于其他细节,如何设置整个应用程序,数据流和ux-flow,但感觉就像您可能想看看CanDeactivate保护方法,该方法可确保用户在离开之前无法离开路线您的Observable<boolean>|Promise<boolean>已解析为true

因此,这是一种异步等待,直到您的服务确认服务器上的一切已更改的方式。

[更新]

这取决于您的用户确认实现方式,但有些方面...

waitForServiceToConfirmWhatever(): Observable<boolean> {
    return yourService.call(); //this should return Observable<boolean> with true emitted when your server work is done
  }

canDeactivate(): Observable<boolean> {

    if(confirm('do you want to leave?') == true)
      return this.waitForServiceToConfirmWhatever();
    else
      Observable.of(false)
  }

09-20 00:37