RXJS和Angular - 我应该使用ReplaySubject和Observable吗?

时间:2018-04-20 15:00:40

标签: javascript angular rxjs

我已经构建了一个模式对话框,允许开发人员在正文中指定自己的内容。它底部有两个按钮 - 取消

开发者实现他们自己的模态,可以选择订阅/不订阅“是”或“取消”按钮。

我可以选择很多选项,用于从Modal发送信号回到单击是或取消的页面。我可以使用 BehaviourSubject 重播主题可观察 EventEmitter

我希望模式在单击是或取消时关闭,然后继续告诉调用页面发生了某些事情。

我已添加 .do()以在订阅者收到通知之前关闭模式。我还在 ngAfterViewInit()中添加了默认订阅,没有人处理说取消事件。

问题:我应该以这种方式成为ReplaySubject和Observable还是有更好的方法来解决这个问题?

modal.ts

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit, AfterViewInit {
  // Outputs
  @Output() onYesClicked: Observable<void>;
  @Output() onNoClicked: Observable<void>;
  @Output() onCancelClicked: Observable<void>;

  private yesReplaySubject: ReplaySubject<void> = new ReplaySubject<void>();
  private noReplaySubject: ReplaySubject<void> = new ReplaySubject<void>();
  private cancelReplaySubject: ReplaySubject<void> = new ReplaySubject<void>();

  constructor() {
    this.configuration = new DefaultModalConfigurationBuilder().build();
    // Do a follow up action of hiding the modal when a replay subject is triggered
    this.onYesClicked =     this.yesReplaySubject.do(x => this.hide());
    this.onNoClicked =      this.noReplaySubject.do(x => this.hide());
    this.onCancelClicked =  this.cancelReplaySubject.do(x => this.hide());
  }

 public ngAfterViewInit() {
    // Some subscription set up incase no one handles the cancel click etc...
    this.onYesClicked.subscribe();
    this.onNoClicked.subscribe();
    this.onCancelClicked.subscribe();
  }

  private yesClicked = (): void => this.yesReplaySubject.next(null);
  private noClicked = (): void => this.noReplaySubject.next(null);
  private cancelClicked = (): void => this.cancelReplaySubject.next(null);
}

modal.html

<ng-content></ng-content>
<div class="pull-right">
  <button class="btn btn-primary"
          [disabled]="!form.valid"
          *ngIf="configuration.modalButtonConfiguration.yesButtonEnabled"
          (click)="yesClicked()">
    {{configuration.modalButtonConfiguration.yesButtonText}}
  </button>
  <button class="btn btn-primary"
          *ngIf="configuration.modalButtonConfiguration.cancelButtonEnabled"
          (click)="cancelClicked()">
    {{configuration.modalButtonConfiguration.cancelButtonText}}
  </button>
  <button class="btn btn-primary"
          *ngIf="configuration.modalButtonConfiguration.noButtonEnabled"
          (click)="noClicked()">
    {{configuration.modalButtonConfiguration.noButtonText}}
  </button>
</div>

app.html

<app-modal title="Modal Demo (onYesClicked)="handleYesClicked()">
  <form novalidate>
    <p>My modal content</p>
  </form>
</app-modal>

app.ts

...
private onYesClicked(): void {
// Do something here
}
...

0 个答案:

没有答案