繁体   English   中英

来自地图的角度 NgRX 返回值不可观察?

[英]Angular NgRX return value from map is not observable?

我试图理解,为什么我的来自 AuthService 的 http 调用返回Observable<CurrentUserInterface>不会从 map 函数内的 NgrX register$效果函数内部返回 observable:

@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) {

  }
}

所以在 map((currentUser: CurrentUserInterface) 内部,它不应该是 Observable 类型吗?为什么它仍然有效?

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,
  },
}

map是一个运算符,接受一个值并返回一个值。

如果要返回另一个 Observable,则需要使用高阶 observable, mergeMapswitchMapexhaustMapconcatMap

有关更多信息,请参阅https://rxjs.dev/guide/higher-order-observables

NgRx 希望你返回一个 Observable,在 NgRx 内部订阅效果并将所有发射分派到商店。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM