cannot unsubscribe ActionsSubject from ngrx/store

冷暖自知 提交于 2021-02-10 06:32:13

问题


I use ngrx/store to implement login actions which gets date from subscribe to a store. The login component is a modal, when I type a wrong password, I get data.type === 'LOGIN_FAILED', however, when I close the modal and re-open it, the data action is still LOGIN_FAILED instead of INIT. Therefore, the login actions are not unsubscribe, I tried to manually unsubscribe the subscription, but it does not work. How can I unsubscribe the login actions properly?

import { Component, OnInit, ViewChildren, OnDestroy } from '@angular/core';

// shared
import { ToasterService } from '../../shared/providers/toaster-service/toaster.service';

// ngx-bootstrap
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

// ngrx
import { ActionsSubject } from '@ngrx/store';

// rxjs
import { Subscription } from 'rxjs/Subscription';

  loading = <boolean>false;
  actionSub = new Subscription();
  errorMessage = <string>'';

constructor(
    private actionsSubj: ActionsSubject,
    private toastService: ToasterService,
    private bsModalRef: BsModalRef,
  ) {
    this.actionSub = this.actionsSubj.subscribe((data: any) => {
      // listen to action of setting tokens successfully / failed
      console.log(data);
      if (data.type === 'LOGIN_FAILED') {
        if (data.payload.error.error.data.type === 'WrongCredentialsException') {
          // hide spinner for login button
          this.loading = false;
          this.errorMessage = 'Wrong Credentials';
        else {
          this.loading = false;
          this.toastService.showError('An error happened when trying to login. Please try again later.');
        }
      } else if (data.type === 'SET_TOKEN') {
        this.bsModalRef.hide();
      }
    });
  } 

  ngOnDestroy() {
    this.actionSub.unsubscribe();
  }

回答1:


This is because ActionsSubject is a BehaviorSubject under the hood, meaning it will store the latest action.

For your case you should be using ScannedActionsSubject which is a Subject under the hood.

I would also encourage to handle your forms with @ngrx/effects - https://blog.angularindepth.com/start-using-ngrx-effects-for-this-e0b2bd9da165



来源:https://stackoverflow.com/questions/52623229/cannot-unsubscribe-actionssubject-from-ngrx-store

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!