我用以下3个动作创建了一个动作文件:
export const showLoading = createAction(`[application] Show warning notification`);
export const hideLoading = createAction(`[application] Show error notification`);
export const showHttpResponseError = createAction(`[application] Show success notification`, props<{ error: HttpErrorResponse, nextAction: Action }>());
export type Actions = ReturnType<
typeof showLoading |
typeof hideLoading |
typeof showHttpResponseError
>;
然后我创建了一个这样的效果文件:
@Injectable()
export class ApplicationEffects
{
constructor(private actions$: Actions, private dialogsService: DialogsService, public notificationsService: NotificationService, private router: Router) { }
@Effect() public erroHandler$ = this.actions$
.pipe(
ofType(ApplicationActions.showHttpResponseError.type),
switchMap(action => {
const emptyAction = { type: 'noop' };
const error = HttpErrorHandler.handle(action.error);
if (error.redirectTo != null) {
this.router.navigate([error.redirectTo]);
return of(emptyAction);
}
if (action.error.status === 400) {
this.notificationsService.notifyWarning('AVISO', error.messages);
}
else {
this.dialogsService.errorDialog('ERRO', error.messages[0]);
}
return action.nextAction ? of(action.nextAction) : of(emptyAction);
},
));
}
但是由于某些原因,VS Code智能感知无法识别switchMap
中的动作类型,而是说其类型为never
:
我想念什么吗?又或者我该如何执行它的类型,因为该动作是使用ngrx动作创建者创建的,因此我没有明确的类型。
答案 0 :(得分:1)
出于完整性考虑,有多种方法:
1)ofType
运算符的类型
ofType<AddAction>(CounterActions.AddAction)
2)输入已注入的动作,就像您已经回答过一样(从NgRx 7开始)
constructor(private actions$: Actions<CounterActions.Actions>
3)与createEffect
结合使用createAction
(从NgRx 8开始)
foo$ = createEffect(() => this.actions$.pipe(
ofType(addAction),
...
);
答案 1 :(得分:0)
为了将来参考,如果有人遇到相同的问题,解决方案是键入注入的actions$
变量:
private actions$: Actions<ApplicationActions.Actions>
然后,智能感知就起作用了,您无需在switchMap
中强制输入类型