如何使用Angular 8 NgRx函数方法调度另一个有效的动作?

问题描述 投票:0回答:2

我的开发环境并不表示有问题(绿色),但是运行它时会发生错误。 (我将获取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。只是不可用。

actions.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);

effect.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;
                }),
            );
        })
    ));
}
angular typescript ngrx-effects
2个回答
0
投票

catchError希望您返回可观察到的,所以也许可以使用catchError尝试类似的操作:

of

0
投票

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

类似=>的东西>

catchError((err) => { // this will run
    console.log(err);
    return of(fromActions.loginFailed());
}),

前一段时间遇到此问题,并发现Wes Grimes(Angular的Google Developer Expert和NgRx核心团队成员)的这篇文章确实很有帮助。catchError

© www.soinside.com 2019 - 2024. All rights reserved.