我正在为 Angular 应用程序编写导航组件。我有以下代码。我想避免多重订阅反模式。我正在为 RxJs 语法和走哪条路(forkJoin、mergeMap 等)而苦苦挣扎。
我如何重构这些,以删除订阅中的订阅。
这是我所拥有的,目前有效,但在订阅中有订阅:
@Component({
selector: 'ehrcc-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
applicationName: string = 'AppName';
userDisplayName: string = '';
isAuthorizedUser: boolean = false;
isAdminUser: boolean = false;
groupsList: MemberGroup[] = [];
constructor(private userService:UserService,
private auditService: UserAuditService,
private router: Router) { }
ngOnInit() {
this.getDisplayName();
this.userService.getGroupMembershipsForUser().subscribe(members =>{
this.groupsList = members;
for (let g of this.groupsList){
if (g.id === this.userService.usersGroupId){
this.isAuthorizedUser = true;
this.router.navigate(['/workItem']);
}
if (g.id === this.userService.adminGroupId){
this.isAdminUser = true;
}
}
this.logUserInfo(); <---- ANTI-PATTERN
});
}
getDisplayName(){
this.userService.getSignedInAzureADUser().subscribe(
(user) => this.userDisplayName = user.displayName,
(error: any) => {
return console.log(' Error: ' + JSON.stringify(<any>error));
});
}
logUserInfo(){
var audit = new UserAudit();
audit.Application = this.applicationName;
audit.Environment = "UI";
audit.EventType= "Authorization";
audit.UserId = this.userDisplayName;
audit.Details = ` User Is Authorized: ${this.isAuthorizedUser}, User Is Admin: ${this.isAdminUser}`;
this.auditService.logUserInfo(audit)
.subscribe({
next: (id)=> console.log('Id created: '+ id),
error: (error: any) => console.log(' Error: ' + JSON.stringify(<any>error) )
});
}
}