-1

为了能够使管理员只能选择删除其他管理员而不是自己,我需要能够存储当前登录用户的 ID。以下是从经过验证的管理员中删除管理员权限的按钮的格式。

<td *ngIf="user.userRoleID == 1 && user.userID != loggedUserID" style="padding-left: 10px;">
 <button style="width: 100%;" (click)="removeAdmin(user.userID)" class="btn btn-warning btn-sm">Remove
   admin
 </button>
</td>

有人可以解释一下如何获取代码的“loggedUserID”部分吗?我正在使用 spring boot 和 angular 来创建这个应用程序。

4

2 回答 2

0

在您的组件中,您需要定义此“loggedUserID”变量。

我提供了一些示例代码,例如,如何连接一切,但您可以自由使用自己的组件类/方法/服务。

用户组件

     export class UserComponent {

      loggedUserID: string;


    constructor(private userService: UserService ) { }

      getUser() {
      this.userService.getUserDetails().subscribe(user => {
          this.loggedUserID = user.id;
        });
}

用户服务

 @Injectable({
      providedIn: 'root',
    })
    export class UserService {


      public getUserDetails(): Observable<User> {

        return this.http.get<User>(url)
                  .pipe(map(data => {
             return data.body;
            }));

      }

}

用户模型

export class User {
id: string,
name: string,
email: string

}

于 2019-06-17T12:31:02.877 回答
0

最简单的方法是使用服务:

@Injectable({
  providedIn: 'root',
})
export class AuthenticationService {
  private currentUser: User; // Here, store the full user or the user id, depending your needs.

  constructor() {
    // [...]
  }

  public login(): void {
    // [...] your call to the API and others...
    this.currentUser = data.user; // Assuming your API returns the user after authentication.
  }

  public getCurrentUser(): User {
    return this.user; // Here you get the current user.
  }

  // [...] other methods
}

然后,您可以使用依赖注入在您的任何组件中引用它:

// [...]
export class YourComponent implements OnInit {
  // [...]

  constructor(private authService: AuthenticationService) {
  }

  ngOnInit() {
    this.loggedUserID = this.authService.getCurrentUser().id; // set the loggedUserID.
  }
}

请注意,以下代码有效,因为此服务是单例:

在 Angular 中有两种方法可以使服务成为单例:

  • 为 @Injectable() providedIn 属性的值声明根
  • 将服务包含在 AppModule 或仅由 AppModule 导入的模块中
于 2019-06-17T12:30:13.723 回答