0

I am following this tutorial https://www.concretepage.com/angular-2/ngrx/ngrx-entity-example. I have now Firestore as my backend. I can retrieve 'LOAD_ALL_ARTICLES' from Firestore. But my code breaks when I try to listen for the 'ADD' action. Any ideas please?!

import { Injectable } from '@angular/core';
import { Action } from '@ngrx/store';
import { Actions, Effect } from '@ngrx/effects';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/mergeMap';
import * as fromActions from '../actions/article.actions';
import * as fromReducer from '../reducers/article.reducer';



//import { ArticleService } from '../services/article.service';
import { Article } from '../models/article';

import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

@Injectable()
export class ArticleEffects {

  constructor(
    private actions$: Actions,
    private afs: AngularFirestore
  ) {}

  @Effect()
  loadAllArticles$: Observable<Action> = this.actions$
    .ofType(fromActions.ArticleActionTypes.LOAD_ALL_ARTICLES)
    .switchMap(() =>
      const ref = this.afs.collection<Article>('articles');
      return ref.snapshotChanges().map(arr => {
      return arr.map(action => {
        const data = action.payload.doc.data() as Article;
        const id = action.payload.doc.id;
        return { id, ...data };
      })
    })


  .map(data => new fromActions.LoadArticlesSuccess({ articles: data }));

//Listen for the 'ADD' action
        @Effect()
        addArticle$: Observable<Action> = this.actions$
        .ofType(fromActions.ArticleActionTypes.ADD_ARTICLE)
        .map((action: fromActions.AddArticle) => action.payload)
        .switchMap( payload => {
          const ref = this.afs.doc<Article>(`articles/${payload.article.id}`);
          return Observable.fromPromise(ref.set(payload.article));
        })


  }

}
Orbicalaz
  • 1
  • 1

1 Answers1

0

I believe you need to switchMap first:

@Effect()
    addArticle$: Observable<Action> = this.actions$
    .ofType(fromActions.ArticleActionTypes.ADD_ARTICLE)
    .switchMap((action: fromActions.AddArticle) => of(action.payload))
    .map( payload => {
      const ref = this.afs.doc<Article>(`articles/${payload.article.id}`);
      return Observable.fromPromise(ref.set(payload.article));
    })
ye-olde-dev
  • 1,168
  • 2
  • 17
  • 29