Angular SSR 网站在转到实际路径之前重定向到登录页面

Angular SSR website redirects to login page before going to actual path

我使用 Angular SSR,当我刷新页面时,它先进入登录页面,然后进入所需页面。

我也使用 cookie 来存储令牌。

canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.tokenService.isAuthenticated$.pipe(
  map(isAuth => {
   if (!isAuth) {
     this.router.navigate(['auth']).then();
     return false;
   }
   return true;
  })
);

}

const routes: Routes =  [
{
  path: 'auth',
  canActivate: [AuthGuard],
  loadChildren: () => import('./main/auth/auth.module').then(m => m.AuthModule)
},
{
  path: '', resolve: {mainInfo: MainResolverService}, component: MainComponent, children: [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'home', loadChildren: () => import('./main/modules/global/home/home.module').then(m => m.HomeModule)},
    {path: 'faq', loadChildren: () => import('./main/modules/global/faq/faq.module').then(m => m.FaqModule)},
    {path: 'cooperation-request', loadChildren: () => import('./main/modules/global/cooperation-request/cooperation-request-module').then(m => m.CooperationRequestModule)},
    {path: 'contact-us', loadChildren: () => import('./main/modules/global/contact-us/contact-us.module').then(m => m.ContactUsModule)},
    {path: 'mentors', loadChildren: () => import('./main/modules/global/mentors/mentors.module').then(m => m.MentorsModule)},
    {path: 'category', loadChildren: () => import('./main/modules/global/category/category.module').then(m => m.CategoryModule)},
    {path: 'about', loadChildren: () => import('./main/modules/global/about/about.module').then(m => m.AboutModule)},
    {path: 'webinar/:id/:title', loadChildren: () => import('./main/modules/global/webinar/webinar.module').then(m => m.WebinarModule)},
    {path: 'user', canActivate: [AuthenticatedGuard], loadChildren: () => import('./main/modules/secured/user.module').then(m => m.UserModule)},
  ]
}

];

这是因为API是在浏览器上调用的,而API必须在Express js中调用。 可以通过cookie-parser包在Express中调用cookies。

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());