简体   繁体   English

订阅的角度返回结果为 Observable

[英]Angular return result of Subscription as Observable

I have a component that upon button click calls a save() method from a StorageManagerService :我有一个组件,在单击按钮时从StorageManagerService调用save()方法:

// component.ts
onSaveClick(): void {
  this.storageManager
    .save(<objectToSave>)
    .pipe(take(1))
    .subscribe({
      next: (success: boolean) => {
        if (success) {
          // do stuff
        } else {
          // do other stuff
        }
      },
    });
}

That storageManager is an adapter to another service that handles conditional logic.该 storageManager 是另一个处理条件逻辑的服务的适配器。 So StorageManagerService.save() looks like the following:因此StorageManagerService.save()如下所示:

// StorageManagerService
save(<objectToSave>): Observable<boolean> {
  if (<someCondition>) {
    this.modalService
      .openDialogWithComponent(
        SaveSystemContainerComponent,
        { data: { <someData> } },
        this.matDialog
      )
      .afterClosed()
      .pipe(take(1))
      .subscribe({
        next: (success: boolean) => {
          if (success) {
            // special handling

            return this.localStorageService.save(<objectToSave>);
          }

          return of(false);
        },
      });
  }
  else {
    return this.localStorageService.save(<objectToSave>);
  }
}

While LocalStorageManagerService has the concrete implementation for storing data:LocalStorageManagerService有存储数据的具体实现:

// LocalStorageManagerService
save(<objectToSave>): Observable<boolean> {
  if (this.storageAvailable()) {
    localStorage.setItem(<objectToSave>.id, JSON.stringify(<objectToSave>));
    return of(true);
  }

  console.error('local storage not available or disabled');
  return of(false);
}

LocalStorageService inherits from an abstract class that all storage services have to implement. LocalStorageService继承自所有存储服务都必须实现的抽象类。 The idea is that when migrating from localStorage to an actual database in the future, I only have to change the variable in StorageManagerService and don't have to modify 20+ places in the application.思路是,以后从localStorage迁移到实际的数据库时,我只需要改变StorageManagerService的变量,不必修改应用程序中的20多个地方。

The problem I'm having is that in certain conditions the user has to input additional data before I can store it.我遇到的问题是,在某些情况下,用户必须输入额外的数据才能存储它。 That input happens through a modal appearing.该输入通过模态出现发生。 Now TypeScript tells me that the if-case in StorageManagerService doesn't return anything (which is correct).现在 TypeScript 告诉我StorageManagerService中的 if-case 不返回任何内容(这是正确的)。

How can I return the result from subscribe.next() in StorageManagerService to the calling function?如何将StorageManagerService subscribe.next()的结果返回给调用函数? I think I'm missing an rxjs operator.我想我缺少一个 rxjs 运算符。

If someone subscribes to save, you can refactor the method to:如果有人订阅保存,您可以将该方法重构为:

save(objectToSave): Observable<boolean> {
  if (someCondition) {
    return this.modalService
      .openDialogWithComponent(
        SaveSystemContainerComponent,
        { data: { someData } },
        this.matDialog
      )
      .afterClosed()
      .pipe(
        take(1),
        switchMap((success: boolean) => {
          if (success) {
            // special handling

            return this.localStorageService.save(objectToSave);
          }
          return of(false);
        })
      );
  } else {
    return this.localStorageService.save(objectToSave);
  }
}

Also, your LocalStorageManagerService should only do the actual save when a subscription is made to the return of save , not only when save is called:此外,您的LocalStorageManagerService应该只在订阅save返回时执行实际save ,而不仅仅是在调用save时:

save(objectToSave): Observable<boolean> {
  return defer(() => {
    if (this.storageAvailable()) {
      localStorage.setItem(objectToSave.id, JSON.stringify(objectToSave));
      return of(true);
    }

    console.error('local storage not available or disabled');
    return of(false);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM