gpt4 book ai didi

javascript - 页面路由在 Angular 8 中无法正常工作

转载 作者:行者123 更新时间:2023-11-28 03:13:29 25 4
gpt4 key购买 nike

我尝试在登录成功后重定向。但有时有效,有时无效。我不明白为什么会这样。我正在使用 metronic 主题。

这是我的代码:

Auth 模块说明:

const routes: Routes = [
{
path: '',
component: AuthComponent,
children: [
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent,
data: {returnUrl: window.location.pathname}
},
{
path: 'register',
component: RegisterComponent
},
{
path: 'forgot-password',
component: ForgotPasswordComponent,
}
]
}
];

应用程序模块路由:

const routes: Routes = [
{path: 'auth', loadChildren: () => import('app/views/pages/auth/auth.module').then(m => m.AuthModule)},

{
path: '',
component: BaseComponent,
canActivate: [AuthGuard],
children: [
{
path: 'dashboard',
loadChildren: () => import('app/views/pages/dashboard/dashboard.module').then(m => m.DashboardModule),
},
{
path: 'po-admin',
loadChildren: () => import('app/views/pages/po-admin/po-admin.module').then(m => m.POAdminModule),
},
{
path: 'mail',
loadChildren: () => import('app/views/pages/apps/mail/mail.module').then(m => m.MailModule),
},
{
path: 'ecommerce',
loadChildren: () => import('app/views/pages/apps/e-commerce/e-commerce.module').then(m => m.ECommerceModule),
},
{
path: 'ngbootstrap',
loadChildren: () => import('app/views/pages/ngbootstrap/ngbootstrap.module').then(m => m.NgbootstrapModule),
},
{
path: 'material',
loadChildren: () => import('app/views/pages/material/material.module').then(m => m.MaterialModule),
},
{
path: 'wizard',
loadChildren: () => import('app/views/pages/wizard/wizard.module').then(m => m.WizardModule),
},
{
path: 'error/403',
component: ErrorPageComponent,
data: {
type: 'error-v6',
code: 403,
title: '403... Access forbidden',
desc: 'Looks like you don\'t have permission to access for requested page.<br> Please, contact administrator',
},
},
{path: 'error/:type', component: ErrorPageComponent},
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: '**', redirectTo: 'dashboard', pathMatch: 'full'},
],
},

{path: '**', redirectTo: 'error/403', pathMatch: 'full'},
];

Auth模块->登录组件oninit和提交方法

ngOnInit(): void {
this.initLoginForm();
// redirect back to the returnUrl before login
this.route.queryParams.subscribe(params => {
this.returnUrl = params.returnUrl || '/';
});
}


submit() {
const controls = this.loginForm.controls;
/** check form */
if (this.loginForm.invalid) {
Object.keys(controls).forEach(controlName =>
controls[controlName].markAsTouched()
);
return;
}

this.loading = true;

const authData = {
email: controls.email.value,
password: controls.password.value,
};
this.auth
.login(authData.email, authData.password)
.pipe(
tap(user => {
if (user) {
debugger;
localStorage.setItem('currentUser', JSON.stringify(user));
if(this.rememberMeChecked){
localStorage.setItem('remember_me_email', user.email);
}else{
localStorage.removeItem('remember_me_email');
}
this.router.navigate([this.returnUrl]);; // Main page
} else {
this.authNoticeService.setNotice(this.translate.instant('AUTH.VALIDATION.INVALID_LOGIN'), 'danger');
}
}),
takeUntil(this.unsubscribe),
finalize(() => {
this.loading = false;
this.cdr.markForCheck();
})
)
.subscribe();
}

和授权守卫:

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private auth: AuthService
) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.auth.currentUserValue;
if (currentUser) {
// logged in then return true
return true;
}

this.router.navigate(['/auth/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}

当用户从配置文件身份验证服务中单击时调用注销方法:

logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}

那么这应该是什么情况呢?我很感激任何帮助。谢谢。

最佳答案

我找到了这个案例。

它与身份验证保护 currentUser 值有关。我忘记在身份验证服务登录实现后进行设置。我在获取用户后设置了 currentUserSubjectValue 的下一个值:

this.currentUserSubject.next(user);

所以我确实这样做了,然后问题就解决了:

login(email: string, password: string): Observable<User> {
debugger;
if (!email || !password) {
return of(null);
}
return this.getAllUsers().pipe(
map((result: User[]) => {
if (result.length <= 0) {
return null;
}

const user = find(result, (item: User) => {
return (item.email.toLowerCase() === email.toLowerCase() && item.password === password);
});

if (!user) {
return null;
}

user.password = undefined;
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
})
);

关于javascript - 页面路由在 Angular 8 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59875558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com