【问题标题】:Angular async pipe and object property角度异步管道和对象属性
【发布时间】:2016-09-05 15:33:27
【问题描述】:

我需要使用没有 ngFor 的异步管道。我需要检查用 observable 异步加载的对象的属性。

这是我想要的,但不起作用:

 <ion-item *ngIf="user$.anonymouse | async">
     <ion-label>Login</ion-label>
 </ion-item>

//编辑:当我使用上面的代码时出现此错误

异常:[!user$.anonymouse | 中管道“AsyncPipe”的参数“true”无效SettingsPage@27:22 中的异步]

有什么办法可以解决这个问题吗?

我知道我可以在 Ctrl 中订阅这个 observable 并将值存储到普通变量中,但我不想这样做,因为性能等原因。

【问题讨论】:

标签: angular ionic-framework rxjs


【解决方案1】:

错误非常准确,因为 *ngIf 指令需要 truefalse 并使用结果表达式来确定是否在 DOM 中呈现 HTML 元素。

异常:[!user$.anonymouse | 中管道“AsyncPipe”的参数“true”无效SettingsPage@27:22 中的异步]

您拥有的表达式是 user$.anonymouse,其计算结果为真,但不幸的是,您不能将此指令与 async 管道一起使用。例如,async 管道“转换”(也称为“管道”)输入,在 @​​987654329@ 指令的范围内公开结果输出。

管道需要三种可能的类型之一,定义如下 (detailed about AsyncPipe):

transform(obj: Observable&lt;any&gt;| Promise&lt;any&gt;| EventEmitter&lt;any&gt;)

有什么办法可以解决这个问题吗?

是的,您可以按照设计使用它。例如在*ngFor 指令中:

<ion-item *ngFor="(user$ | async)?.anonymouse">
     <ion-label>Login</ion-label>
</ion-item>

或者您可以完全移除管道,因为 *ngIf 指令不需要它:

<ion-item *ngIf="user$.anonymouse">
     <ion-label>Login</ion-label>
</ion-item>

【讨论】:

  • 需要澄清 AsyncPipe 与 NgFor 的使用,如上所述。表达式*ngFor="user$.anonymouse | async" 会将user$anonymouse 属性传递给AsyncPipe,我相信它是undefined,因为user$ 是一个可观察对象,而不是可观察对象的输出。为了在 user$ 上运行 AsyncPipe,然后访问结果上的 anonymouse 属性,您需要使用 *ngFor="(user$ | async)?.anonymouse"
  • 我认为@Sean 的评论应该是一个答案并标记为已接受的答案。接受的答案给出了很好的解释;但是,正如 Sean 所指出的,(user$ | async)?.anonymouse 是 OP 需要做的(对我有用的!谢谢!)
【解决方案2】:

正如@Sean 在 cmets 中所述,您的*ngIf 语句应基于返回的user$ 对象的结果对象属性anonymouse。因此:

<ion-item *ngIf="(user$ | async)?.anonymouse">
     <ion-label>Login</ion-label>
</ion-item>

这对我有用,这里是一个如何使用下面管道结果的示例:

组件

 message$: Observable<{message: string}>;

  private messages = [
    {message: 'You are my hero!'},
    {message: 'You are the best hero!'},
    {message: 'Will you be my hero?'}
  ];

  constructor() { this.resend(); }

  resend() {
    this.message$ = Observable.interval(500)
      .map(i => this.messages[i])
      .take(this.messages.length);
  }

查看

<h2>Async Hero Message and AsyncPipe</h2>
<p>Message: {{ (message$ | async)?.message }}</p>
<button (click)="resend()">Resend</button>`

可以在here找到一个工作示例。

【讨论】:

    【解决方案3】:
    <!-- This is needed to wait for async pipe to resolve -->
    <div *ngIf="user$ | async as user"> 
    
       <!-- Only on resolve of async pipe -->
       <ion-item *ngIf="user.whateverPropertyYouWantToCheck">
            <ion-label>Login</ion-label>
        </ion-item>
    </div>
    

    请注意,我从user$ 切换到user,如果您愿意,可以使用相同的变量名,但这更清楚地表明该值不再是异步管道。

    【讨论】:

    • 这是我认为最好的答案。
    【解决方案4】:

    isAnonymous$ = user$.pipe(map(user => user?.anonymouse));

    <ion-item *ngIf="user$.anonymouse | async">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-15
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2019-04-10
      • 2021-02-02
      • 1970-01-01
      相关资源
      最近更新 更多