簡體   English   中英

如何重定向頁面取決於 angular 8 中的條件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM