【发布时间】:2021-01-28 14:58:04
【问题描述】:
我在 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() {}
}
【问题讨论】:
-
你也可以分享登录组件映射吗?
-
是的。我编辑了我的帖子,以便您也可以看到登录和身份验证模块。
-
请分享 ResetPasswordComponent 代码
-
ResetPasswordComponent 也在编辑中添加。
标签: angular