Home > database >  Angular NgRX return value from map is not observable?
Angular NgRX return value from map is not observable?

Time:07-11

I am trying to understand, why my http Call from AuthService, which returns an Observable<CurrentUserInterface> does not return an observable from inside my NgrX register$ effect function inside the map function:

@Injectable()
export class AuthService {
  constructor(private http: HttpClient) {

  }

  register(data: RegisterRequestInterface): Observable<CurrentUserInterface> {
    const url = environment.apiUrl   'users'
    return this.http.post<AuthResponseInterface>(url, data).pipe(map((response:AuthResponseInterface) => response.user));
  }
}


@Injectable()
export class RegisterEffect {

  register$ = createEffect(
    () => this.actions$.pipe(
      ofType(registerAction), 
      switchMap(({request}) => {
      return this.authService.register(request).pipe(
        map((currentUser: CurrentUserInterface) => registerSuccessAction({currentUser})),
        catchError(() => of(registerFailureAction()))
      );
      
    }
  )));

  constructor(private actions$: Actions, private authService : AuthService) {

  }
}

so inside the map((currentUser: CurrentUserInterface), shouldn't it be of type Observable? Why does it still work?

export interface CurrentUserInterface {
  id: number,
  createdAt: string,
  updatedAt: string,
  username: string,
  bio: string | null,
  email: string,
  image: string | null,
  token: string,
}

export interface AuthResponseInterface {
  user: CurrentUserInterface
}

export const registerAction = createAction(
 ActionTypes.REGISTER,
  props<{ request: RegisterRequestInterface}>()
)

export interface RegisterRequestInterface {
  user: {    
    username: string,
    email: string,
    password: string,
  },
}

CodePudding user response:

map is an operator takes a value and returns a value.

If you want to return another Observable, you need to use higher-order observables, mergeMap, switchMap, exhaustMap, concatMap.

For more info see https://rxjs.dev/guide/higher-order-observables.

NgRx wants you to return an Observable, internally NgRx subscribes to the effect and dispatches all emisions to the store.

  • Related