What to store in ngrx / store when using angularfire2?

I am starting to learn angular2 and have enrolled in ngrx / store (I have no previous experience with downsizing) and firebase app. Now I can't get my head around how to store firebase objects, arrays and stuff in the store. Should I put them the way I put them FirebaseListObservable

in storage , for example af.database.list('/items')

? This seems like a good fit (the component can just do store.select ("items") and the template can subscribe to it, and for mutations I can still fire events in the store where I will mutate the list using reducers), but I I guess not because this list might be changed from outside the store (by some other app user who subscribes to the same list). Or does it depend on the specific case?

If not, where should I store a reference to this firebase object and what should I put into storage?

+3


source to share


1 answer


it is recommended that only serializable content be placed in the storage:

It is highly recommended that you only post simple serializable objects, arrays and primitives in your store. It is technically possible to insert non-serializable items into the repository, but this can interfere with the ability to save and save store content, as well as interfere with travel debugging.

The asynchronous nature of AngularFire2 observables means that you will most likely want to integrate them using @ ngrx / effects . Effects essentially listen for a specific action, perform some (possibly asynchronous) side effect, and then (usually) emit another action.

How you do this will depend on what you want to do.

For example, if you want to use FirebaseListObservable

to execute queries, you can use typical actions READ_ITEMS

, READ_ITEMS_SUCCESS

and READ_ITEMS_ERROR

and effect like this:



@Effect()
readItems$ = this.actions$
  .ofType('READ_ITEMS')
  .switchMap(() => this.af.database
    .list('/items')
    .first()
    .map(items => ({ type: 'READ_ITEMS_SUCCESS', payload: items }))
    .catch(() => Observable.of({ type: 'READ_ITEMS_ERROR', payload: error.toString() }))
  );

      

However, if you want to listen for real-time changes from FirebaseListObservable

, you can do something like this:

@Effect()
refreshItems$ = this.af.auth
  .switchMap((authState) => authState ?
    this.af.database
      .list('/items')
      .map(items => ({ type: 'REFRESH_ITEMS', payload: items })) :
    Observable.of({ type: 'REFRESH_ITEMS', payload: [] })
  );

      

Note that the second effect does not listen to the action. Instead, it responds to the authentication state and will invoke actions REFRESH_ITEMS

after the user has authenticated, etc.

In both cases, the action being performed will contain a payload of an array of elements that can be processed by a reducer for storage in storage.

+5


source







All Articles