1

我正在为 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) )
    });
  }
}

4

2 回答 2

2

我发现了这个问题,因为我正在搜索为什么某些subscribe代码块在没有明显原因的情况下被多次执行。

我发现这是由于服务返回了一些尚未加载正确数据的Observable 。因此,我用auditTime解决了这个问题:

忽略源值毫秒,然后从源Observableduration发出最新值。

因此,使用问题的代码,可以使用该运算符添加管道:

import { auditTime, ... } from 'rxjs/operators';

this.userService.getGroupMembershipsForUser().
 .pipe(auditTime(1E3)) // delays for 1 second and gets the most recent value
 .subscribe(members => { ... });
于 2019-09-25T15:55:45.033 回答
1

您可以使用 forkJoin https://www.learnrxjs.io/operators/combination/forkjoin.html

forkJoin({
   displayName: this.userService.getSignedInAzureADUser() // This will give you the 
   observable subscription value,
   groupMemberShip:this.userService.getGroupMembershipsForUser() 
})

订阅该 forkJoin 后,您将获得一个包含所有值的对象,您可以从中调用 logUserInfo,所有可观察对象都需要完成()才能发出 forkJoin

于 2019-07-19T11:34:46.430 回答