在@ngrx/effects 中调用 http 之前的调度操作

baj*_*032 1 rxjs ngrx-effects angular

我想为我使用 rxjs 的效果进行 http 调用。现在我的问题是我想像{ type: LoaderActions.LOADER_START }在 http 调用之前一样调度另一个动作。所以用户可以在请求 Http 调用时看到加载屏幕,一旦请求完成,我想调度另一个动作{ type: LoaderActions.LOADER_END }

如何使用 rxjs 运算符实现此目的?我对何时在 rxjs 中使用哪个运算符感到非常困惑。

auth.effects.ts

import { Injectable } from '@angular/core';
import { Observable, of, concat } from 'rxjs';
import { Action, Store } from '@ngrx/store';
import { Actions, Effect, ofType } from '@ngrx/effects';
import * as AuthActions from './auth.actions';
import * as LoaderActions from '../../loader/store/loader.actions';
import {
  map,
  mergeMap,
  switchMap,
  debounce,
  debounceTime,
  tap,
  startWith
} from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json; charset=utf-8'
  })
};
@Injectable()
export class AuthEffects {
  @Effect()
  signInAction$: Observable<Action> = this.actions$.pipe(
    ofType(AuthActions.TRY_SIGN_IN),
    mergeMap(action =>
      this.http
        .post(
          'http://localhost:8081/auth',
          JSON.stringify({
            username: action['username'],
            password: action['password']
          }),
          httpOptions
        )
        .pipe(
          map(data => {
            if (data['message'] === 'successs') {
              this.router.navigate(['/todo']);
              return { type: AuthActions.SET_AUTH_FLAG, payload: true };
            } else {
              return { type: AuthActions.SET_AUTH_FLAG, payload: false };
            }
          })
        )
    )
  );

  constructor(
    private actions$: Actions,
    private http: HttpClient,
    private router: Router
  ) {}
}
Run Code Online (Sandbox Code Playgroud)

mar*_*tin 5

您可以使用concat第一个源 Observable 将作为加载操作的地方。

@Effect()
signInAction$: Observable<Action> = this.actions$.pipe(
  ofType(AuthActions.TRY_SIGN_IN),
  concatMap(action => concat(
    of({ type: LoaderActions.LOADER_START }),
    this.http...
    of({ type: LoaderActions.LOADER_END }),
  ))
)
Run Code Online (Sandbox Code Playgroud)

concat运营商将确保按顺序创建的操作。

  • @baj9032 使用 `concatMap` 而不是 `mergeMap`。 (2认同)