You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17中Auth Guard始终显示Toastr错误消息的问题及解决

问题解决

问题根源是SSR(服务端渲染)。Angular 17创建项目时若启用了SSR,服务端生成的错误提示会直接嵌入HTML中,无法在客户端移除。

解决方法:修改angular.json配置文件:

原配置:

...
"server": "src/main.server.ts",
"prerender": true,
"ssr": {
  "entry": "server.ts"
}
...

修改为:

...
"server": "src/main.ts"
...

问题详情

在Angular 17项目中使用Toastr展示提示信息,同时配置了Auth Guard。

Auth Guard代码如下:

export const authGuard: CanActivateFn = (route, state) => {

  const accountService = inject(AccountService);
  const toastr = inject(ToastrService);

  return accountService.currentUser$.pipe(
    map(user => {
      if(user){
        console.log("Calling me valid user",user);
        return true;
      }
      else{
        console.log("Calling me invalid user",user);
        toastr.error('you shall not pass!');
        return false;
      }
    })
  )
};

路由配置:

{
    path:'',
    runGuardsAndResolvers : 'always',
    canActivate : [authGuard],
    children : [
      {path:'members',component:MemberListComponent},
      {path:'members/:id',component:MemberDetailComponent},
      {path:'lists',component:ListsComponent},
      {path:'messages',component:MessagesComponent},
    ]
  },

登录后刷新页面时,VSCode终端输出console.log("Calling me invalid user",user);,浏览器控制台输出console.log("Calling me valid user",user);,但浏览器仍会显示Toastr错误消息toastr.error('you shall not pass!');。

内容的提问来源于stack exchange,提问作者mestu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 02:52:09