JavaScript构造函数调用

时间:2018-07-03 02:22:36

标签: javascript angular typescript redux

嗨,所以在我正在开发的应用程序中,我有一个构造函数,用于检查redux存储中是否有各种组件传递的错误消息。它会显示错误或成功消息。但是,一旦用户关闭横幅(单击x)并且我转到另一个人的投资组合,横幅将不再显示错误或成功消息

constructor(private store: Store<State>) {
  store
  .select(StatusBannerState)
  .map(data => {
    return data.status_banner;
  })
  .subscribe(banner_state => {
    if (banner_state.success_list.length > 0) {
      this.showBanner = true;
      this.bannerMessage = this.createSuccessBannerMessage(
        banner_state.success_list
      );
      setTimeout(() => {
        this.store.dispatch(new BannerDimissesSuccessMessage());
        this.bannerMessage = this.createErrorBannerMessage(
          banner_state.error_list
        );
      }, 5000);
    } else if (banner_state.error_list.length > 0) {
      this.bannerMessage = this.createErrorBannerMessage(
        banner_state.error_list
      );
    } else {
      this.showBanner = false;
      this.bannerMessage = '';
    }
  });
}

我现在在createErrorMessage函数中调用此测试函数以显示或隐藏功能(我在angular应用程序的HTML组件中调用它)

showOrHideBanner(errorWidget) {
  errorWidget.length === 0
   ? (this.showBanner = false)
   : (this.showBanner = true);
}

我还有另一种在初始化时清除redux存储的方法

ngOnInit() {
  this.store.dispatch(new UserDismissesEverything());
}

在用户关闭横幅后再次检查错误消息的最佳方法是什么

更新:关闭代码

onCloseClick() {
  this.close.emit(true);
  this.show = false;
  this.clearTimeout(this.timeoutId);
}

HTML组件代码

<div class="mt-1 container">
    <div class="alert-box">
    <div *ngIf="bannerMessage" class="px-3 mb-1">
                    <glass-alert-box
                        (close)="hideTheBanner()"
                      [success]="bannerMessageType == 'success'">{{ bannerMessage}}
                    </glass-alert-box>
            </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

constructor(private store: Store<State>) {

}

ngOnInint() {
    this.store.dispatch(new UserDismissesEverything());
}

ngAfterViewInint() {
    this.store.select(StatusBannerState).map(data => {
        return data.status_banner;
    }).subscribe(banner_state => {
        if (banner_state.success_list.length > 0) {
            this.showBanner = true;
            this.bannerMessage = this.createSuccessBannerMessage(banner_state.success_list);
            setTimeout(() => {
                this.store.dispatch(new BannerDimissesSuccessMessage());
                this.bannerMessage = this.createErrorBannerMessage(banner_state.error_list);
            }, 5000);
        } else if (banner_state.error_list.length > 0) {
            this.bannerMessage = this.createErrorBannerMessage(banner_state.error_list);
        } else {
            this.showBanner = false;
            this.bannerMessage = '';
        }
    });
}