问题
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