簡體   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