Angular 角度观测值2

Angular 角度观测值2,angular,rxjs,Angular,Rxjs,下面是我的部分angular2组件模板html。 “searchTickets$”是一个可观察的对象数组 <table class="table table-condensed" *ngIf="searchTickets$"> <thead> <tr> <th><h3>Ticket ID</h3></th> </tr> </thead> <tbody&

下面是我的部分angular2组件模板html。 “searchTickets$”是一个可观察的对象数组

<table class="table table-condensed" *ngIf="searchTickets$">
<thead>
    <tr>
        <th><h3>Ticket ID</h3></th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let ticket of searchTickets$  | async">
        <td><small>{{ticket.ticketID}}</small></td>     
    </tr>
</tbody>
</table>

票号
{{ticket.ticketID}
我的意图是,仅当可观察到 返回一条或多条记录

在*ngIf条件下需要修改什么才能实现这一点。

您应该试试

<table class="table table-condensed" *ngIf="(searchTickets$ | async)?.length > 0">

正如@xe4me所说:

<table class="table table-condensed" *ngIf="(searchTickets$ | async)?.length">

如果您想处理来自TS的可观察数据

@Component({
  ...
})
export class YourComponent implements OnDestroy {
  public searchTickets: any;
  private searchTicketsSub: Subscription;

  constructor(private yourService: any) {
    this.searchTickets =
      // let say you have the observable coming from a service that
      // makes an HTTP call 
      yourService
        .getSearchTicket()
        .subscribe((searchTickets: any) => this.searchTickets = searchTickets);
  }

  ngOnDestroy() {
    // then, don't forget to unsubscribe
    this.userSub.unsubscribe();
  }
}

无,尝试初始化您的searchTickets,删除ngIf,如果数组为空,则不会显示任何内容,搜索后您将该数组设置为响应数据,如果响应有内容,则将呈现该元素ID您尝试
*ngIf=“(searchTickets$|async).length”
?@PierreDuc,是的,它抛出“无法读取null的属性'length'”错误。开始时,tit将为null,您需要先进行如下安全检查:*ngIf=“(searchTickets$| async)?.length“searchTickets$是可观察的,您无法获得这样的长度,您首先需要订阅它!哇,这是一个地狱般的编辑。要获取@xe4me代码,您应该删除您的答案。我只能获取@xe4me的代码。我的答案来自这里。这肯定有效,但问题是你会订阅该源两次!如果源不会发射太多东西,这不是什么大问题,否则你需要仔细检查源。@xe4me我的回答不会发射两次;)那么,“共享”是运营商吗?
<tr *ngFor="let ticket of searchTickets$  | async">
@Component({
  ...
})
export class YourComponent {
  public searchTickets: any;

  constructor(private yourService: any) {
    this.searchTickets = yourService
      .getSearchTicket()
      .share();

    // share allows you to avoid duplicate subscriptions
  }
}
@Component({
  ...
})
export class YourComponent implements OnDestroy {
  public searchTickets: any;
  private searchTicketsSub: Subscription;

  constructor(private yourService: any) {
    this.searchTickets =
      // let say you have the observable coming from a service that
      // makes an HTTP call 
      yourService
        .getSearchTicket()
        .subscribe((searchTickets: any) => this.searchTickets = searchTickets);
  }

  ngOnDestroy() {
    // then, don't forget to unsubscribe
    this.userSub.unsubscribe();
  }
}