如果巡逻人员未授予您访问权限,则显示警报

时间:2018-08-13 20:40:05

标签: angular

我正在使用Route Guard,除非用户已登录,否则它无法访问页面。但是我还想向用户显示一条消息,告知他必须先登录。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

@Injectable()
class OnlyLoggedInUsersGuard implements CanActivate { 
  constructor(private userService: UserService) {}; 

  canActivate() {
    console.log("OnlyLoggedInUsers");
    if (this.userService.isLoggedIn()) { 
      return true;
    } else {
      window.alert("You don't have permission to view this page"); 
      return false;
    }
  }
}

并且:

{
  path: 'artist/:artistId',
  component: ArtistComponent,
  canActivate: [OnlyLoggedInUsersGuard, AlwaysAuthGuard], 
  children: [
    {path: '', redirectTo: 'tracks'},
    {path: 'tracks', component: ArtistTrackListComponent},
    {path: 'albums', component: ArtistAlbumListComponent},
  ]
}