![](/img/trans.png)
[英]Redirect from within Angular controller if condition is met at start of page
[英]How to redirect page depends on condition in angular 8
我正在尝试从登录页面重定向页面。我有一个标志用于检查购物车是否为空。 我可以将该标志设置为 true 或 false。 我想在登录后重定向页面取决于标志和登录与否。我尝试过但没有工作。请帮助任何人找到解决方案。
login.component.ts:
onSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
this.loading = true;
this.authenticationService.login(this.f.username.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
//if cart is not empty
// if(this.flag==true){
// this.router.navigate(['./billing']);
// }
//if cart is empty
//else{
// this.router.navigate(['./cartempty']);
// }
//this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
order.component.ts:
goTOloginbilling(){
//if Not logged
// if(????){
// this.router.navigate(['./login']);
// }
//if cart is not empty
// else if(this.flag==true){
// this.router.navigate(['./billing']);
// }
//if cart is empty
//else if(this.flag==false){
// this.router.navigate(['./cartempty']);
// }
}
演示: https : //stackblitz.com/edit/angular-8-registration-login-example-gnjckr?file= app/ order/order.component.ts
查看您的代码,我发现了一些问题。
在login.component.ts 中,变量标志声明如下:
flag: true
我想你想要写flag: boolean= true;
在同一个文件中,在onSumbit 函数中,当您调用登录函数时,在收到您写的响应后:
this.router.navigate(['./billing']);
但是在 app.routing.module.ts 中,路由是:
{ path: '', component: BillingComponent, canActivate: [AuthGuard] },
所以你必须写:
this.router.navigate(['']);
所以总结一下:
onSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
this.loading = true;
this.authenticationService
.login(this.f.username.value, this.f.password.value)
.subscribe(
data => {
//if cart is not empty
if (this.flag == true) this.router.navigate([""]);
else {
this.router.navigate(["cartempty"]);
}
},
error => {
this.alertService.error(error);
this.loading = false;
}
);
}
显然,您可以在app.routing.ts 中为 cartEmpty 定义路由:
{ path: 'cartempty', component: CartemptyComponent },
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.