Async pipe not working with Subject

China☆狼群 提交于 2019-12-12 09:08:46

问题


I have the following BehaviorSubject in a service:

  isAuthenticated = new BehaviorSubject<boolean>(false);

And I am using it as follows in a component:

  authenticated: Observable<boolean>;

  constructor(private accountService: AccountService) { }

  ngOnInit() {
    this.authenticated = this.accountService.isAuthenticated.asObservable();
  }

And in the template I do something like :

  <li class="login-button" *ngIf="!authenticated | async">
    <a (click)="authenticate()">Log in</a>
  </li>
  <li *ngIf="authenticated | async">
    <a>Logged in</a>
  </li>

The issue is that I dont see any of the two li, although the assumption is that the first one should appear since I am assigning the initial value of the Subject to false.

What am I doing wrong?


回答1:


I suspect its the order of operations - you need parenthesis around your subscription:

<li class="login-button" *ngIf="!(authenticated | async)">



回答2:


I thought of posting a solution using ng-if-else which is maybe even more intuitive in your particular case:

<li class="login-button" *ngIf="(authenticated | async); else unauthenticated">
  <a>Logged in</a>
</li>
<ng-template #unauthenticated>
  <a (click)="authenticate()">Log in</a>
</ng-template>

Alternatively you could puth both cases inside a ng-template:

<li class="login-button" *ngIf="(authenticated | async); then authenticated else unauthenticated"></li>
<ng-template #authenticated ><a>Logged in</a></ng-template>
<ng-template #unauthenticated><a (click)="authenticate()">Log in</a></ng-template>

Hope it is of any use to other people ending up here.



来源:https://stackoverflow.com/questions/48319388/async-pipe-not-working-with-subject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!