angular - 如果一次失败,为什么角度 ngx 效果不起作用?
问题描述
我使用 Angular 6 和 Ngrx 效果。它的登录效果
@Effect({dispatch: false})
login$ = this.actions$.pipe(
ofType<Login>(AuthActionTypes.Login),
tap(action => {
localStorage.setItem(environment.authTokenKey, action.payload.authToken);
console.log('login effect');
this.store.dispatch(new UserRequested());
}),
);
它发送了用户请求效果
@Effect({dispatch: false})
loadUser$ = this.actions$
.pipe(
ofType<UserRequested>(AuthActionTypes.UserRequested),
withLatestFrom(this.store.pipe(select(isUserLoaded))),
filter(([action, _isUserLoaded]) => !_isUserLoaded),
mergeMap(([action, _isUserLoaded]) => this.auth.getUserByToken()),
tap(data => {
console.log('login effect');
if (data) {
this.store.dispatch(new UserLoaded({ user: data['user'] }));
localStorage.setItem('options', JSON.stringify(data['options']));
// localStorage.setItem("permissions", data['user'].permissions_list);
data['user'].permissions_list.forEach((item) => {
this.permissionsService.addPermission(item.name);
});
} else {
this.store.dispatch(new Logout());
}
}, error => {
this.store.dispatch(new Logout());
})
);
如果这个效果被调用并且至少失败一次,它就不会被再次调用。为什么?
解决方案
因为需要控制流。如果您的流有错误,它会按预期停止。
如果您不希望它停止,请考虑将catchError
运算符与throwError
函数一起使用,或者只是在订阅中捕获错误。
现场观看:
不工作
rxjs.throwError('mocked error')
.subscribe(
() => console.log('You should not see this message'),
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>
在职的
rxjs.throwError('mocked error')
.subscribe(
() => console.log('You should not see this message'),
() => console.log('You should see this message')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>
工作国际清算银行
rxjs.throwError('mocked error')
.pipe(rxjs.operators.catchError(err => rxjs.of('some mocked replacement value')))
.subscribe(
() => console.log('You should see this message'),
() => console.log('You should not see this message')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>
推荐阅读
- node.js - 如何在 Node.js 中处理比特币支付?
- bootstrap-4 - 使用 Promise 防止关闭 Bootstrap 模式
- angular - 在 ionic 项目中使用 Angular 库时,必须从注入上下文调用 inject()
- telegram - 我的 Telegram Bot 已添加到垃圾邮件频道。如何删除它?
- multithreading - 在 MVVM 架构中使用领域时出现线程错误
- java - springboot中@oneToMany双向映射的问题
- node.js - React 私有路由真的安全吗?
- c# - 数组元素为空,除了第一个
- python - 在 Django 中处理某些 CRUD 异常的正确方法是什么
- c++ - 如何按层次顺序构造二叉树