【发布时间】:2018-01-26 14:07:29
【问题描述】:
在注册过程中我有 3 个 http 调用:向身份验证提供商注册,在 api 中创建帐户,然后登录。
如果使用身份验证提供商注册失败(例如帐户已存在),它仍会尝试在 api 中创建帐户。 如果我在 @Effect 末尾添加一个 catch,第二次尝试(比如更正的凭据)将不再调用该效果。
如何防止后续的(accountSercice.CreateAccount 和 authenticationService.Login)switchMaps 运行?
@Effect() AccountSigningUp$ = this.actions$
.ofType(ACCOUNT_SIGNING_UP)
.map((action: AccountActions.AccountSigningUp) => action.payload)
.switchMap(signUpModel => this.authenticationService.SignUp(signUpModel)
.catch(err => {
let signUpModel = new SignUpModel();
signUpModel.message = err;
return Observable.of(new AccountSignUpFailed(signUpModel))
})
.switchMap(signUpModel => this.accountService.CreateAccount((signUpModel as SignUpModel))
.catch(err => {
let signUpModel = new SignUpModel();
signUpModel.message = err;
return Observable.of(new AccountSignUpFailed(signUpModel))
})
)
.switchMap(loginModel => this.authenticationService.Login((loginModel as LoginModel))
.map(tokenModel => {
this.tokenService.Save(tokenModel);
return new AccountLoggedIn();
})
.catch(err => {
let loginModel = new LoginModel();
loginModel.message = err;
return Observable.of(new AccountLoginFailed(loginModel))
})
)
.map(() => new AccountCreated())
);
【问题讨论】:
-
仅供参考,从 catch 运算符返回
Observable.of(...)就像标准的try/catch一样,代码将在 catch 之后继续(在本例中为流)。从 catch 运算符返回Observable.throw(...)就像在try/catch中重新抛出一个错误,它会冒泡直到被捕获(在这种情况下,跳过流中的所有其他运算符,直到它遇到捕获或错误回调订阅)。我只是分享一下,以供您理解。正确的答案已经提出(设置单独的效果来触发彼此的成功)。
标签: angular typescript rxjs ngrx ngrx-effects