简体   繁体   中英

Angular page is redirected to main page

I have multiple routes defined in Angular routing and i entered a reset-password url but it navigate to login page automatically.

const routes: Routes = [
  {
    path: "",
    component: DashboardComponent,
    pathMatch: "full",
    canActivate: [AuthGuardService],
  },
  {
    path: "reset-password",
    component: ResetPasswordComponent,
    pathMatch: "full",
  },
  {
    path: "dashboard",
    component: DashboardComponent,
    pathMatch: "full",
    canActivate: [AuthGuardService],
  },
  {
    path: "auth",
    data: { preload: true },
    loadChildren: () =>
      import("./authentication/authentication.module").then(
        (x) => x.AuthenticationModule
      ),
  },
  {
    path: "not-authorized",
    pathMatch: "full",
    canActivate: [AuthGuardService],
    component: NotAuthorizedComponent,
  },
  { path: "**", component: NotFoundComponent },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      preloadingStrategy: CustomPreloadingService,
      initialNavigation: "enabled",
    }),
  ],
  exports: [RouterModule],
  providers: [RouterExtService],
})
export class AppRoutingModule {}

Auth Guard Service is applied which check that token is present in localstorage if not present there it will redirect user to /auth/login page which is in another module.

But on reset-password i did not even add the AuthGuard to check this setting but when i open the page direct url "http://localhost:4200/reset-password" then it navigate to login page automatically

Here is the AuthModule

const authRoutes: Routes = [{ path: "login", component: LoginComponent }];
@NgModule({
  declarations: [LoginComponent, ForgotPasswordComponent],
  imports: [SharedModule, RouterModule.forChild(authRoutes)],
  entryComponents: [ForgotPasswordComponent],
})
export class AuthenticationModule {}

Here is the Login Component

errors: AllValidationErrors[] = []
  
  constructor(
    private router: Router,
    private authService: AuthServiceService,
    private loader: LoaderService,
    private fb: FormBuilder,
    private toaste: CustomToastrService,
    private modalService: NzModalService,
  ) {}

  LogInForm = this.fb.group({
    userName: ['', Validators.required],
    userPassword: ['', Validators.required],
  })

  ngOnInit() {
    if (this.authService.isLoggedIn()) {
      this.router.navigate(['/'])
    }
  }

  onSubmit() {
    this.credentialMissing = false
    this.blocckedByAdmin = false
    this.errors = []
    if (this.LogInForm.valid) {
      this.loader.Show(this.div)
      let credentials: any = this.LogInForm.value
      this.authService
        .login(credentials.userName, credentials.userPassword)
        .subscribe(
          (api) => {
            if (api.success) {
              var apiResponse = api.response
              //Case 1 : User is InActive
              if (apiResponse && apiResponse.inActive == true) {
                this.loader.Hide(this.div)
                this.LogInForm.reset()
                this.blocckedByAdmin = true
              } else {
                //CASE 2 : User is Active but OTP not required
                if (
                  apiResponse &&
                  (apiResponse.inActive == null ||
                    apiResponse.inActive == false) &&
                  apiResponse.twoFactorAuthType == ''
                ) {
                  this.loader.Hide(this.div)
                  let detail = {
                    rights: api.response.authRights,
                    committees: api.response.authCommitees,
                  }
                  this.authService.setUserDetail(detail)
                  this.authService.setToken(api.response.token).then(() => {
                    this.router.navigateByUrl('')
                  })
                } else {
                  // Case 3 : User is Active Confirm OTP
                  if (
                    apiResponse.otpBasedUserId != null &&
                    apiResponse.otpBasedUserId > 0
                  ) {
                    this.loader.Hide(this.div)
                    this.toaste.Success(api.message)
                    this.ValidateOTPModel(apiResponse.otpBasedUserId)
                  } else {
                    this.toaste.Error('Problem in sending OTP ,try again')
                  }
                }
              }
            } else {
              this.loader.Hide(this.div)
              this.LogInForm.reset()
              this.credentialMissing = true
            }
          },
          (error) => {
            this.loader.Hide(this.div)
            this.credentialMissing = true
            this.LogInForm.reset()
          },
        )
    } else {
      this.errors = getFormValidationErrors(this.LogInForm)
    }
  }

Here is the Reset Password Component.

@Component({
  selector: "app-reset-password",
  templateUrl: "./reset-password.component.html",
  styleUrls: ["./reset-password.component.scss"],
})
export class ResetPasswordComponent implements OnInit {
  constructor(
    private activeRoute: ActivatedRoute,
    private formBuider: FormBuilder,
    private userService: UserService,
    private router: Router,
    private toaster: CustomToastrService
  ) {}

  resetEmail: string = "";
  resetDate: string = "";
  div: string = "data-div";
  errors: AllValidationErrors[] = [];
  passwordValues: IResetPassword;
  ngOnInit() {
    this.resetEmail = this.activeRoute.snapshot.queryParams["email"];
    this.resetDate = this.activeRoute.snapshot.queryParams["dt"];
    this.resetPasswordForm.patchValue({
      email: this.resetEmail,
      dateEncrypted: this.resetDate,
    });
  }

  resetPasswordForm = this.formBuider.group({
    confirmPassword: ["", [Validators.required]],
    newPassword: ["", [Validators.required]],
    email: [""],
    dateEncrypted: [""],
  });

  ResetPassword() {
    this.errors = [];
    this.passwordValues = this.resetPasswordForm.value;
    if (this.resetPasswordForm.valid) {
      if (this.passwordValues.email == "") {
        this.errors.push({
          error: "",
          keyError: "Email",
          key: "required ",
        });
      }
      if (this.passwordValues.dateEncrypted == "") {
        this.errors.push({
          error: "",
          keyError: "Date ",
          key: "required ",
        });
      }
      this.errors = [];
      if (
        this.passwordValues.confirmPassword != this.passwordValues.newPassword
      ) {
        this.errors.push({
          error: "",
          keyError: "Not Similar To Confirm Password",
          key: "New Password ",
        });
      } else {
        this.userService
          .ResetPasswordViaLink(this.passwordValues)
          .subscribe((pwd) => {
            if (pwd && pwd.success) {
              this.router.navigateByUrl("/auth/login");
            } else {
              this.toaster.Error(pwd.message);
            }
          });
      }
    } else {
      this.errors = getFormValidationErrors(this.resetPasswordForm);
    }
  }

  ResetForm() {}
}

Can you try with removing the pathMatch: "full". In my projects i use it without the pathMatch and it works as it should

  {
    path: "reset-password",
    component: ResetPasswordComponent
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM