简体   繁体   中英

Page routing doesn't work properly with Angular 8

I am trying to redirect after login is successful. But it works sometimes , it doesn't work sometimes. I couldn't understand why it is happening like this. I'm using metronic theme.

So here is my codes:

Auth module rotes:

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,
            }
        ]
    }
];

App module routes:

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 module ->login component oninit and submit methods

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

And auth guard:

@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;
    }
}

When user click from profile auth service call logout method:

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

So what should be case for this? I appreciate any helps. Thanks.

I found the case.

Its about the auth guard currentUser value. I forgot to set after auth service login impletemtation.I set the next value of currentUserSubjectValue after get the user:

this.currentUserSubject.next(user);

So I did like this then it has been solved:

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

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