具有嵌套订阅的 returns 布尔值的函数

Function that returns boolean with nested subscription

我有一排用 ngFor 循环创建的 mat-chexboxes。

   <div class="permission-one" *ngFor="let permission of permissions">
    <mat-checkbox [disabled]="(!isEdit && userIndex !== i) || (isEdit && userIndex !== i)" [checked]="isChecked(fauxUser.userId, permission)" (change)="checkboxSelected($event, permission.code)"></mat-checkbox>
  </div>

为了查看创建时是否需要选中该复选框,我正在调用 isChecked(),如下所示:

isChecked(userId: number, permission: Permission): boolean {
 this.adminService.getUserAccess(this.companyId, userId)
 .subscribe((userAccessRes: UserPermission) => {
   for (const special of userAccessRes.specialPrograms) {
    if(special.programCode === permission.code && special.userAccessId !==0) 
      {
        return true;
      } else {
        return false;
      }
    }
  });
}

然而,由于与订阅的嵌套,我无法弄清楚如何将 if 语句的 return 值获取到适当的级别,以便 return 它用于函数。 现在我的错误是 "A function whose declared type is neither 'void' nor 'any' must return a value." 是否可以将我拥有的功能用于我想要的功能? 任何 tips/suggestions 将不胜感激

你不能直接return一个布尔值(你的return语句在订阅回调中,而不是组件方法本身),你需要return另一个Observable 从您的角度使用 RxJS's map operator and use the async pipe

脚本端:

import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

// ...

isChecked(userId: number, permission: Permission): Observable<boolean> {
  return this.adminService.getUserAccess(this.companyId, userId).pipe(
    map((userAccessRes: UserPermission) => {
      // test your permission here and return true or false
    })
  );
}

视图:

<mat-checkbox [checked]="isChecked(fauxUser.userId, permission) | async"></mat-checkbox>

注意:在 *ngIf 等指令中调用组件方法有时被认为是不好的做法,因为它会导致性能问题。尽可能使用计算属性。