【发布时间】:2018-08-30 09:19:30
【问题描述】:
我想使用 rxjs 的效果进行 http 调用。现在我的问题是我想在 http 调用之前发送另一个动作,比如{ type: LoaderActions.LOADER_START }。所以用户可以在请求 Http 调用时看到加载屏幕,一旦请求完成,我想调度另一个动作 { type: LoaderActions.LOADER_END }。
如何使用 rxjs 运算符实现这一点?我很困惑何时在 rxjs 中使用 which 运算符。
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
) {}
}
【问题讨论】:
标签: angular rxjs ngrx-effects