【发布时间】:2019-11-10 17:06:21
【问题描述】:
尝试减少 订阅数并使用等效的flatMap\switchMap\do\tap rxjs下面提到的代码的运算符。 它正在工作,但我知道这不是最好的方法。 代码的作用如下: 首先 - 有一个凭证检查(用户名和通行证): A. 如果它获取用户数据,它会 resetLoginAttempts - 将登录尝试次数重置为 0 并路由到不同的路由。 B. 如果不是 (A) - 它增加登录尝试次数 - 将登录尝试次数增加 1。服务在增加后取回登录次数。根据它检查 - 如果登录尝试 >= 3 则它生成验证码,它也返回 observable。
//loginSrv.Login - return observable of userData (json)
//sessionService.resetLoginAttempts - return observable of void
//sessionService.increaseLoginAttempts - return observable of any (json)
//loginSrv.GetCaptcha - return observable of any (svg image)
subscriptions : Subscription[] = [];
login()
{
this.subscriptions.push(this.loginSrv.Login(userName, password).subscribe(result =>
{
if (result && result.userData)
{
this.sessionService.resetLoginAttempts().subscribe();
this.router.navigateByUrl('');
}
else
{
this.subscriptions.push(this.sessionService.increaseLoginAttempts().subscribe(result =>
{
if (result.loginAttempts >= 3)
{
this.generateCaptcha();
}
}, error =>
{
throwError(error))
}
));
}
}, (error => throwError(error))
));
}
generateCaptcha()
{
this.subscriptions.push(this.loginSrv.GetCaptcha().subscribe(response =>
{
this.captcha = response;
this.setCaptchaImage();
},
error => throwError(error)));
}
【问题讨论】:
-
您是否有任何理由保留对订阅的引用?我假设你让他们在销毁时取消订阅?
-
正确 - 这就是原因 - 我在 ngOnDestroy() 事件中这样做
标签: angular rxjs angular2-observables