1
votes

I'm learning ngrx and i'm trying to make a example using metadata (i'm following the NgRx documentation), my problem is that my service is reveiving the type of my action, and i need only the payload.

What i tried:

In my component i make a dispatch passing my user object:

public save() {
  const user: Usuario = this.formGroup.value;
  this.store.dispatch(saveUser(user));
}

This is my action:

export const saveUser = createAction('[Users API] Save User', props<Usuario>());

This is the effect that handle this action:

public saveUser$ = createEffect(() =>
  this.actions$.pipe(
    ofType(saveUser),
    mergeMap((action) => this.usuarioService.save(action))
  )
);

This is my service:

public save(data: T): Observable<any> {
  console.log(data);
  return this.http.post<any>(`${this.apiPath}`, data);
}

My problem is that my service is receiving the type of my action and i need only the object user:

{
  "id": null,
  "nome": "naaame",
  "cidade": "ciiity",
  "type": "[Users API] Save User"
}

I try to pass a object in my action:

this.store.dispatch(saveUser({ user: user }));

But my service is an abstract class, i extend this class in my services to reduce repetead codes, so, in this class i can't use data.user because other services also extend this class and use the same function save().

I also tried to remove the type from the object and return the service without this action:

  public saveUser$ = createEffect(() =>
    this.actions$.pipe(
      ofType(saveUser),
      exhaustMap((action) => {
        const userWithoutType = {...action}
        delete userWithoutType.type
        return this.usuarioService.save(userWithoutType);
      })
    )
  );

This way my service don't receive the type property, but i receive a error from the ngrx:

ERROR Error: Effect "UsuarioEffects.saveUser$" dispatched an invalid action: {"id":5,"nome":"wwww","cidade":"wewe"}

ERROR TypeError: Actions must have a type property

1

1 Answers

2
votes
public saveUser$ = createEffect(() =>
  this.actions$.pipe(
    ofType(saveUser),
    mergeMap((action) => this.usuarioService.save(action.Usuario))
  )
);