如何重定向页面取决于角度8中的条件

问题描述 投票:0回答:1

我正在尝试从登录页面重定向页面。我有一个标志用于检查购物车是否为空。我可以将该标志设置为true或false。我要在登录后重定向页面,具体取决于该标志和是否登录。我已经尝试过但无法正常工作。请帮助任何人找到解决方案。

login.commponent.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

javascript typescript angular7 angular8
1个回答
0
投票

查看您的代码,我看到了相同的问题。

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 },
© www.soinside.com 2019 - 2024. All rights reserved.