【问题标题】:Angular *ngIf with async pipe inner condtion based on the resulting modelAngular *ngIf 与基于结果模型的异步管道内部条件
【发布时间】:2020-08-31 11:08:13
【问题描述】:

如果有人可以解释为什么以下内容没有按预期工作,我会很高兴? hasCreative 是一个布尔值,但无论其真/假值如何,始终显示 <li>。任何建议都会很棒。谢谢。

<ng-container *ngIf="uiModel$ | async as model">
    <ul class="nav" style="padding-bottom: 30px;">
      <li *ngIf="model.hasCreative" class="nav-item">
        <a class="nav-link active" routerLinkActive="active" [routerLink]="['']">Home</a>
     </li>
   </ul>
</ng-container>

export class UserInterfaceModel {
  hasCreative: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class UserInterfaceService {
  user: CognitoUser;
  userLoggedIn = false;
  private userInterfaceModelSubject$: Subject<UserInterfaceModel> = new Subject();
  userInterfaceModel$ = this.userInterfaceModelSubject$.asObservable();

  constructor(private authService: AuthService) {
    combineLatest([this.authService.onUserLoaded$]).subscribe(([currentUser]) => {
      this.user = currentUser;
      this.userLoggedIn = true;
      this.buildUserInterfaceModel();
    });
  }

  buildUserInterfaceModel(){
    const model = new UserInterfaceModel();
    if (this.userLoggedIn && this.user !== null){
      model.hasCreative  = this.user.getSignInUserSession().getIdToken().payload.creative;
    }
    this.userInterfaceModelSubject$.next(model);
  }
}

【问题讨论】:

  • 你能发布 uiModel$ 的内容吗?
  • 如果model.hasCreative = 'false',而不是model.hasCreative = false,我只能看到这种情况发生
  • uiModel$: Observable;构造函数(私有modalService:NgbModal,私有authService:AuthService,私有userInterfaceService:UserInterfaceService){}ngOnInit():无效{this.uiModel$ = this.userInterfaceService.userInterfaceModel$; }
  • 导出类 UserInterfaceModel { hasCreative: boolean; }
  • @Nevnev 你能用UserInterfaceModel 实例的样子更新你的答案吗?因为很明显model.hasCreative 正在解析为true。所以它要么是字符串,要么是其他东西,但绝对不是false

标签: javascript angular asynchronous


【解决方案1】:

试试这个:


<ng-container *ngIf="uiModel$ | async as model; else loading">
    <ul class="nav" style="padding-bottom: 30px;">
      <li *ngIf="model.hasCreative === true " class="nav-item">
        <a class="nav-link active" routerLinkActive="active" [routerLink]="['']">Home</a>
     </li>
   </ul>
</ng-container>

<ng-template #loading>
  Loading stuff...
</ng-template>

如果loading 模板将呈现,则意味着您的Observable 没有价值。如果它也不起作用,请尝试通过添加如下内容来渲染 model.hasCreative 的值:

<span>{{model.hasCreative}}<span>

&lt;ul&gt;标签中查看model.hasCreative是否有true/false值。

【讨论】:

  • 谢谢,我确实尝试过,跨度呈现为真或假,具体取决于它是什么
  • 你的问题解决了吗?
  • 谢谢,是的。我改变了我设置 isCreative 的方式,它起作用了。
  • model.hasCreative = isCreative.toLocaleLowerCase() === 'true' ?真:假;
  • 所以,它是一个string。你说它是boolean 而不是。
猜你喜欢
  • 2018-08-24
  • 2020-08-12
  • 2018-10-11
  • 1970-01-01
  • 2020-08-24
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
相关资源
最近更新 更多