Angular 13中点击关注按钮触发全局状态切换而非单个用户状态切换的问题修复咨询
修复 Angular 13 中关注按钮全局同步切换的问题
这个问题的核心原因很明确:你在组件里用了一个全局的isFollowed布尔变量,所有用户的按钮状态都绑定到这个变量上。不管点击哪个用户的按钮,都会修改这个全局变量,导致所有用户的按钮状态一起切换。
要解决这个问题,我们需要给每个用户单独维护自己的关注状态,而不是用一个全局变量。下面是具体的修复步骤和代码修改:
1. 移除全局状态,给每个用户添加独立的关注状态
首先,删除组件里的isFollowed: boolean;声明。我们要在每个用户对象上添加一个isFollowed属性,用来跟踪该用户是否被当前登录用户关注。
如果你的User接口原本没有这个属性,可以扩展一个新类型:
// 扩展User接口,添加关注状态属性 interface UserWithFollowStatus extends User { isFollowed: boolean; }
然后把组件里的users类型改为UserWithFollowStatus[]。
2. 初始化时加载关注状态
在组件初始化获取用户列表后,需要调用接口获取当前登录用户的已关注列表,然后给每个用户设置对应的isFollowed状态:
export class FollowersComponent implements OnInit { constructor(private userService: UserService, private followerService: FollowerService) { } users: UserWithFollowStatus[]; // 修改类型 follower: Follower; currentUserId: number; // 这里需要替换成你项目中获取当前登录用户ID的方式,比如从AuthService ngOnInit(): void { this.userService.getUsers().subscribe(response => { // 把获取到的用户列表转换为带关注状态的类型 this.users = response.map(user => ({ ...user, isFollowed: false })); // 加载当前用户的已关注列表,更新状态 this.loadCurrentUserFollowees(); }); } private loadCurrentUserFollowees() { // 调用服务获取当前用户的已关注列表 this.followerService.getUserFollowee(this.currentUserId).subscribe(followees => { // 提取已关注用户的ID集合 const followedUserIds = followees.map(followee => followee.id); // 假设FolloweeModel里有id字段对应被关注用户ID // 遍历用户列表,设置每个用户的关注状态 this.users.forEach(user => { user.isFollowed = followedUserIds.includes(user.id); }); }); } // ...其他方法 }
3. 修改关注/取消关注方法,只更新当前用户的状态
原来的方法会修改全局变量,现在我们要找到被操作的用户,单独更新它的isFollowed状态:
followUser(userId: number){ this.followerService.followUser(userId, this.follower).subscribe(response => { // 找到对应的用户,更新其关注状态 const targetUser = this.users.find(user => user.id === userId); if(targetUser) { targetUser.isFollowed = true; } }); } unfollowUser(userId: number){ this.followerService.unfollowUser(userId).subscribe(response => { // 找到对应的用户,更新其关注状态 const targetUser = this.users.find(user => user.id === userId); if(targetUser) { targetUser.isFollowed = false; } }); }
4. 调整模板,绑定每个用户自己的状态
最后修改模板,把原来绑定全局isFollowed的地方,改成绑定每个用户的user.isFollowed:
<app-toolbar></app-toolbar> <div class="main-div" *ngFor="let user of users"> <div class="users"> <img [src]="user.imageUrl" alt="user image" height="50px"> <span>@{{user.username}}</span> <div class="button-div" *ngIf="!user.isFollowed"> <button mat-raised-button color="primary" (click)="followUser(user.id)">Follow</button> </div> <div class="button-div" *ngIf="user.isFollowed"> <button mat-flat-button color="warn" (click)="unfollowUser(user.id)">Unfollow</button> </div> </div> </div>
关键注意点
currentUserId需要根据你的项目认证逻辑来获取,比如从AuthService、localStorage或者后端接口返回的当前用户信息中提取。- 如果后端返回的
FolloweeModel结构不同,需要调整followees.map(followee => followee.id)这部分代码,确保能正确提取被关注用户的ID。
这样修改后,每个用户的关注状态都是独立维护的,点击某个用户的按钮只会改变该用户的按钮状态,不会影响其他用户了。
内容的提问来源于stack exchange,提问作者Ruschisb
相关产品推荐
相关产品推荐

