Estoy tratando de hacer algo simple: después de que se guardó alguna entidad (usando la solicitud http), quiero volver a la ruta de la lista. El problema es: cómo suscribirse a la acción de éxito (¿o puede ser reductor o efecto?)
aquí está mi código de acciones:
static SAVE_POST = '[POST] Save POST'; savePOST(Post): Action { return { type: PostActions.SAVE_POST, payload: Post }; } static SAVE_POST_SUCCESS = '[POST] Save POST Success'; savePOSTSuccess(Post): Action { console.log('action: savePostSuccess') return { type: PostActions.SAVE_POST_SUCCESS, payload:Post }; }estoy usando efectos:
@Effect() savePost$ = this.update$ .ofType(PostActions.SAVE_POST) .map(action => action.payload) .switchMap(post => this.svc.savePost(post)) .map(post => this.postActions.savePOSTSuccess(post));reductor:
const initialState: PostListState = []; export default function (state = initialState, action: Action): PostListState { switch (action.type) { case PostActions.LOAD_POST_SUCCESS: { return action.payload; } case PostActions.SAVE_POST_SUCCESS: { console.log('SavePOST SUCCESS',action.payload) let index = _.findIndex(state, {_id: action.payload._id}); if (index >= 0) { return [ ...state.slice(0, index), action.payload, ...state.slice(index + 1) ]; } return state; } default: { return state; } } }en mi componente quiero suscribirme a la devolución de llamada exitosa:
handlePostUpdated($event) { this.post = this.code; let _post: Post = Object.assign({}, { _id: this.id, name: this.name, text: this.post }); this.store.dispatch(this.postActions.savePOST(_post)); //not have "subscribe" method }Gracias por la ayuda
También puede suscribirse a acciones en componentes:
[...] import { Actions } from '@ngrx/effects'; [...] @Component(...) class SomeComponent implements OnDestroy { destroyed$ = new Subject<boolean>(); constructor(updates$: Actions) { updates$.pipe( ofType(PostActions.SAVE_POST_SUCCESS), takeUntil(this.destroyed$) ) .subscribe(() => { /* hooray, success, show notification alert etc.. */ }); } ngOnDestroy() { this.destroyed$.next(true); this.destroyed$.complete(); } }Basado en esto: https://netbasal.com/listening-for-actions-in-ngrx-store-a699206d2210 con algunas pequeñas modificaciones, ya que desde ngrx 4 ya no hay Dispatcher , sino ActionsSubject :
import { ActionsSubject } from '@ngrx/store'; import { ofType } from "@ngrx/effects"; subsc = new Subscription(); constructor(private actionsSubj: ActionsSubject, ....) { this.subsc = this.actionsSubj.pipe( ofType('SAVE_POST_SUCCESS') ).subscribe(data => { // do something... }); } ngOnDestroy() { this.subsc.unsubscribe(); }necesitas tener un selector que te dé la última publicación
this.latestPost$ = this.store.select(fromRoot.getPost);
luego puede suscribirse a this.latestPost$ observable y redirigir a su nueva ruta suponiendo que haya declarado latestPost$: Observable<Post>; en su componente.
para obtener más detalles, consulte esta aplicación de ejemplo https://github.com/ngrx/example-app