为了能够做到这一点,以便管理员只能选择删除其他管理员而不是自己,我需要能够存储当前登录用户的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来创建此应用程序。
答案 0 :(得分: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()提供的属性的值
- 将服务包括在AppModule或仅由AppModule导入的模块中
答案 1 :(得分:0)
在您的组件中,您需要定义此'loggingUserID'变量。
我提供了一些示例代码,如中所述,如何连接所有内容,但您可以自由使用自己的组件类/方法/服务。
UserComponent
export class UserComponent {
loggedUserID: string;
constructor(private userService: UserService ) { }
getUser() {
this.userService.getUserDetails().subscribe(user => {
this.loggedUserID = user.id;
});
}
UserService
@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
}