Как перенаправить страницу зависит от условия в angular 8 - PullRequest
0 голосов
/ 16 февраля 2020

Я пытаюсь перенаправить страницу со страницы входа. У меня есть один флаг, который проверяет, что корзина пуста или нет. Я могу установить этот флаг 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

1 Ответ

0 голосов
/ 16 февраля 2020

Просматривая ваш код, я увидел некоторые проблемы.

В 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;
        }
      );
  }

Очевидно Вы можете определить маршрут для cartEmpty в app.routing.ts :

{ path: 'cartempty', component: CartemptyComponent },
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...