【问题标题】:Page redirects to homepage when i reload using CTRL + R in Angular 8当我在 Angular 8 中使用 CTRL + R 重新加载时页面重定向到主页
【发布时间】:2020-07-29 12:49:51
【问题描述】:

当我使用 CTRL + R 或 F5 重新加载页面或打开新选项卡时,总是以 8 角重定向到主页。

我的路线设置在这里

const routes: Routes = [
  { path: 'dashboard', component: OrderComponent, canActivate: [AuthGuard] },
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'orders', component: OrderComponent, canActivate: [AuthGuard] },
  { path: 'add-product', component: AddProductComponent, canActivate: [AuthGuard] },
  { path: 'past-orders', component: PastOrdersComponent, canActivate: [AuthGuard] },
  { path: 'today-orders', component: TodayOrdersComponent, canActivate: [AuthGuard] },
  { path: 'schedule-orders', component: ScheduleOrdersComponent, canActivate: [AuthGuard] },
  { path: 'products', component: ProductsComponent, canActivate: [AuthGuard] },
  { path: 'edit-product/:product_id', component: AddProductComponent, canActivate: [AuthGuard] },
  { path: 'invoice/:order_id', component: InvoiceComponent },
  { path: 'accept-order/:order_id', component: SingleOrderComponent, canActivate: [AuthGuard] },
  { path: 'timing', component: TimingComponent, canActivate: [AuthGuard] },
  { path: 'settings', component: SettingsComponent, canActivate: [AuthGuard] },
  { path: '**', component: PageNotFoundComponent },
];

@NgModule({
  // { useHash: true }
  imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload', enableTracing: false, useHash: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

我的功能是打开一个不应重定向到主页的新标签

    const url = this.router.serializeUrl(
      this.router.createUrlTree(['/invoice', '8088299'])
    );

 window.open(url, '_blank');

auth.guard.ts

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree {
    if (!this.authService.isLoggedin()) {
      this.router.navigate(['login']);
});
      return false;
    }

    return true;
  }

}

this.authService.isLoggedin()下面的函数代码不是HTTP请求

 isLoggedin() {
    // `!!` returns boolean
    return !!localStorage.getItem('token');
  }

【问题讨论】:

  • 能否也添加 AuthGuard 的代码。
  • 没有启用AuthGuard的路由会不会出现这个问题?请分享 AuthGuard 代码以便更好地理解?
  • 如何为您的应用程序提供服务?
  • @RahulSingh 添加
  • 你能分享你的 authguard

标签: javascript angular angular8


【解决方案1】:

您必须在身份验证服务中验证您的令牌是否有效,然后以布尔值返回结果并同时重定向到相应的页面。

身份验证服务应如下所示

@Injectable()
export class AuthService {

    constructor() { }

    public isAuthenticated(): boolean {
        const token = localStorage.getItem('token');
        return token != null;
    }
}

假设你有一些路线如下,

/product
/product/:product-id

那么你的路线应该如下启动,

const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent },
  {
    path: 'product',
    canActivate: [AuthGuard],
    children: [
      { path: '', component: ProductComponent },
      { path: ':id', component: ProductIdComponent }
    ]
  },
];

使用这种方式你甚至可以重新加载、重定向或者直接在浏览器中输入网址,进入你需要重定向的动态页面。

在您的本地存储中拥有令牌之前,可以访问产品 ID 页面。

这不是一个好的做法,因为您在客户端身份验证验证上留下了很大的安全漏洞,请尝试使用带有 Promise 和 HTTP 或 JSON Web 令牌的一些服务器端身份验证验证,即使您可以将令牌发送到服务器每次您发送请求并在处理客户端请求之前从服务器端进行验证。

请查看此存储库以详细了解您的解决方案 https://stackblitz.com/github/aslamanver/angular-sample-authguard

【讨论】:

  • 非常感谢它解决了我的问题@Googlian
【解决方案2】:

canActivate 方法在 authService.isLoggedin() 解析之前返回。 authService.isLoggedin() 返回响应后,您需要返回响应。 总是从你的 isLoggedIn 方法返回一个 observable。一旦你这样做了,你的 canActivate 方法可能看起来像这样:

   

    export class AuthGuard implements CanActivate {
    
      constructor(private authService: AuthService, private router: Router) { }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):  Observable<boolean>| Promise<boolean>| boolean{
       return  this.authService.isLoggedin()
            .pipe(
              map(
                response => {
                  if (response === true) {
                    return true;
                  }else{
                       this.router.navigate(['login']);
                       return false;
                  }
                }),catchError((err: HttpErrorResponse) => {
                  this.router.navigate(['login']);
                  return of(false)
                })
            );
        }
      }

【讨论】:

  • 如果一次添加所有代码会很棒。无论如何,您能否在本地存储中添加设置项目的代码?
  • localStorage.setItem('token', received_token);
  • 使用您提供的最少代码,条件应该类似于 if(received_token &amp;&amp; localStorage.getItem('token') == null){ localStorage.setItem('token',received_token) } 。顺便说一句,你是如何获取 received_token 的?
猜你喜欢
  • 2020-07-04
  • 2020-02-18
  • 2021-07-18
  • 2021-01-28
  • 1970-01-01
  • 2017-08-23
  • 2014-02-20
  • 1970-01-01
  • 2020-03-02
相关资源
最近更新 更多