繁体   English   中英

Angular | authguard 阻止所有页面

[英]Angular | The authguard blocks all pages

我需要从 json 中获取值,它根据用户类型返回 true 或 false。 我进行了调试,true 和 false 值是正确的,但尽管如此,页面的 url 还是打不开。 我究竟做错了什么?

auth.guard.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> {
    return new Promise((resolve, reject) => {
      let flagErrors: boolean;
      let flagLabels: boolean;
      this.userService.getProfili().subscribe(response => {
        for (var i = 0; i < response.result.length; i++) {
          const id = response.result[i].id;
          if (this.authService.id == id) {
            flagErrors = response.result[i].flagErrors;
            flagLabels= response.result[i].flagLabels;
            break;
          }
        }
        if (flagErrors) {
          this.router.navigateByUrl('/errors');
          return flagErrors
        }
        if (flagLabels) {
          this.router.navigateByUrl('/label');
          return flagLabels
        }
      });
    });
  }

应用程序路由.ts

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'label', component: LabelsComponent, canActivate: [AuthGuard] },
  { path: 'errors', component: ErrorsComponent, canActivate: [AuthGuard] },
];

你必须从结果中返回值,所以我使用 boolean observable...你必须从 rxjs 添加 map。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.userService.getProfili().pipe(map((res) => {
    for (var i = 0; i < res.result.length; i++) {
      const id = res.result[i].id;
      if (this.authService.id == id) {
        flagErrors = res.result[i].flagErrors;
        flagLabels= res.result[i].flagLabels;
        break;
      }
    }
    if (flagErrors && state.url == 'errors') {
      return true
    }
    if (flagLabels && state.url == 'label') {
      return true
    }
    return false
})

}

canActivate方法中的代码没有返回守卫的预期值,它是boolean值或UrlTree object。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.userService.getProfili().pipe(map((response) => {
    for (let i = 0; i < response.result.length; i++) {
      const userId = response.result[i].id;
      if (this.authService.id == userId) {
        flagErrors = response.result[i].flagErrors;
        flagLabels= response.result[i].flagLabels;
        break;
      }
    }
    if (flagErrors && state.url == 'errors') {
       return this.router.createUrlTree(['/errors'])
    }
    if (flagLabels && state.url == 'label') {
      return this.router.createUrlTree(['/label'])
    }
    return false
})

应用程序路由.ts

const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'label', component: LabelsComponent, canActivate: [AuthGuard] },
{ path: 'errors', component: ErrorsComponent, canActivate: [AuthGuard] },
];

我看不到在这里使用Promise的意义,只有当你需要加载它时,如果需要,请确保使用resolve()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM