首页 > 解决方案 > 如何使用 Angular 8 NgRx 函数方法调度另一个有效的操作?

问题描述

我的开发环境没有提示问题(全绿),但是运行时出现错误。(我会得到 http404 并且 cacheError 会运行。现在可以像“错误测试”一样。)

错误消息:ERROR TypeError: "You provided '() => ({ type })' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. 我看到了,但我想发送loginFailed一个没有道具的动作。

HttpIntercept 是存在的!所以 url 将是http://localhost:PORT/user/login. 只是它不可用。

动作.ts

// imports

export const types = {
    loginStart: '[User] Login start',
    loginSuccess: '[User] Login success',
    loginFailed: '[User] Login fail',
};

export const loginStart = createAction(types.loginStart, props<ILogin>());
export const loginSuccess = createAction(types.loginSuccess, props<IUser>());
export const loginFailed = createAction(types.loginFailed);

效果.ts

import { types } from './actions';
import * as fromActions from './actions';
// and more imports

@Injectable()
export class UserEffects {
    constructor(
        private actions$: Actions,
        private http: HttpClient,
        private router: Router,
    ) {
    }

    loginProcess = createEffect(() => this.actions$.pipe(
        ofType(types.loginStart),
        exhaustMap((action) => {
            return this.http.post<IUser>('/user/login', {
                username: action.username,
                password: action.password,
            }).pipe(
                map(data => {
                    console.log(data);
                    return fromActions.loginSuccess(data);
                }),
                catchError((err) => { // this will run
                    console.log(err);
                    return fromActions.loginFailed;
                }),
            );
        })
    ));
}

标签: angulartypescriptngrx-effects

解决方案


很奇怪,您在编译时没有收到错误,但我认为这可能是因为 RxJScatchError运算符期望返回一个可观察的对象。

像 =>

catchError(err =>
  of(featureActions.LoadFailureAction({ err }))
),

不久前遇到这个问题,发现 Wes Grimes(Google Angular 开发专家和 NgRx 核心团队成员)的这篇文章非常有帮助。 https://itnext.io/ngrx-best-practices-for-enterprise-angular-applications-6f00bcdf36d7


推荐阅读