我使用角度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());
})
);
如果此效果被调用并且至少一次失败,则不会再次调用。为什么?
答案 0 :(得分:0)
因为需要控制流。如果流有错误,它将按预期停止。
如果您不希望它停止,请考虑将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>
有效的BIS
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>