angular - Angular页面被重定向到主页
问题描述
我在 Angular 路由中定义了多个路由,我输入了一个重置密码 url,但它会自动导航到登录页面。
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 服务检查本地存储中是否存在令牌,如果不存在,它将把用户重定向到另一个模块中的 /auth/login 页面。
但是在重置密码上,我什至没有添加 AuthGuard 来检查此设置,但是当我打开页面直接 url “http://localhost:4200/reset-password”时,它会自动导航到登录页面
这是 AuthModule
const authRoutes: Routes = [{ path: "login", component: LoginComponent }];
@NgModule({
declarations: [LoginComponent, ForgotPasswordComponent],
imports: [SharedModule, RouterModule.forChild(authRoutes)],
entryComponents: [ForgotPasswordComponent],
})
export class AuthenticationModule {}
这是登录组件
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)
}
}
这是重置密码组件。
@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() {}
}
解决方案
您可以尝试删除 pathMatch:"full"。在我的项目中,我在没有 pathMatch 的情况下使用它,它可以正常工作
{
path: "reset-password",
component: ResetPasswordComponent
},
推荐阅读
- nsis - Nsis为什么系统传递“0”而不是整数
- c++ - 延迟第 3 方库中静态变量的初始化
- cython - 当扩展模块被垃圾收集时运行 cython 代码
- java - 在java中切换到POST方法不起作用
- web-scraping - 刮 https://socialblade.com/
- angular - 无法在错误“无法确定类 TestComponent 的模块”中找到 TestComponent
- c# - Entity Framework Core悲观锁定行表Mysql
- excel - VBA循环遍历表格并将图表导出到每封电子邮件
- angular - 如何使用 mat-dialog 的 backgroundClick 关闭对话框并将更改的数据发送回父组件
- python - 安装 Python 包将下载、安装和删除其他包