角度异步管道和对象属性

Dan*_*chý 43 rxjs ionic-framework angular

我需要在没有ngFor的情况下使用异步管道.我需要检查与observable异步加载的对象的属性.

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

 <ion-item *ngIf="user$.anonymouse | async">
     <ion-label>Login</ion-label>
 </ion-item>
Run Code Online (Sandbox Code Playgroud)

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

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

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

我知道我可以在Ctrl中将这个observable订阅商店值变成普通变量但是我不想这样做,因为性能等等.

Abd*_*eed 50

正如@Sean的注释中所述,您的*ngIf语句应该基于返回anonymouseuser$对象的结果对象属性.因此:

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

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

零件

 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);
  }
Run Code Online (Sandbox Code Playgroud)

视图

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

可以在这里找到一个工作示例.


Dav*_*ine 36

*ngIf指令期望true或者false使用结果表达式确定是否HTML在DOM中呈现元素时,错误非常准确.

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

你所拥有的表达式的结果是user$.anonymouse真实的,但不幸的是你不能使用async带有这个指令的管道.所述async管道"变换"(也称为"管")的输入暴露所述的范围之内所产生的输出*ngFor指令,例如.

管道需要以下定义的三种可能类型之一(详细说明AsyncPipe):

transform(obj: Observable<any>| Promise<any>| EventEmitter<any>)

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

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

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

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

<ion-item *ngIf="user$.anonymouse">
     <ion-label>Login</ion-label>
</ion-item>
Run Code Online (Sandbox Code Playgroud)

  • 如上所述,需要澄清AsyncPipe与NgFor的使用.表达式`*ngFor ="user $ .anonymouse | async"`会将`user $`的`anonymouse`属性传递给AsyncPipe,我相信这将是`undefined`,因为`user $`是一个可观察的,而不是输出可观察的.为了在`user $`上运行AsyncPipe,然后在结果上访问`anonymouse`属性,你需要使用`*ngFor ="(user $ | async)?. anonymouse"`. (61认同)
  • 我认为@Sean的评论应该是一个答案并标记为已接受的答案.接受的答案给出了一个很好的解释; 然而,正如肖恩所指出的,`(用户$ | async)?.anonymouse`是OP需要做的事情(以及对我有用的东西!谢谢!) (3认同)

Tim*_*ode 7

我认为这也可能有用:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

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

  • 这是我认为最好的答案。 (4认同)