Javascript 可观察角度2不为';异步管道触发的t

Javascript 可观察角度2不为';异步管道触发的t,javascript,angular,typescript,rxjs,Javascript,Angular,Typescript,Rxjs,考虑一下angular2/rxjs/typescript的这个简单片段 public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(ship => this.roomByShipService.getRoomsB

考虑一下angular2/rxjs/typescript的这个简单片段

  public rooms: Observable<Room[]>;      

  constructor ( ... ) {

    this.rooms = this.inspectShipSubject
      .do(() => console.log('foo'))
      .switchMap(ship => this.roomByShipService.getRoomsByShip(ship));

    //this.rooms.subscribe(); // <-- [1]
  }
公共房间:可见;
构造函数(…){
this.rooms=this.inspectShipSubject
.do(()=>console.log('foo'))
.switchMap(ship=>this.roomByShipService.getRoomsByShip(ship));

//this.rooms.subscribe();//我不确定这是否是一个好的解决方案(或者只是一个解决方案),但您可以将每个事件存储在一个数组中,然后循环该数组:

this.rooms=[];
this.roomsObservable = this.inspectShipSubject
      .switchMap(ship => this.roomByShipService.getRoomsByShip(ship))
      .observe(next =>this.rooms.push(next));

编辑:我刚刚意识到,我不确定您是要显示房间列表还是只显示最新收到的房间。如果您只需要最新的房间,那么我认为您不需要ngFor指令。

好的,我不知道为什么,但诀窍是在
此上使用
行为主题
而不是
主题

这可以很好地工作,并由模板正确触发

  public rooms$: Observable<Room[]>;

  private inspectShipSubject: BehaviorSubject<Ship> = new BehaviorSubject<Ship>(null);

  constructor(
    ...
  ) { }

  ngOnInit() {
    this.rooms$ = this.inspectShipSubject.switchMap(ship => this.roomByShipService.getRoomsByShip(ship));
  }

  @Input()
  set ship(ship: Ship) {
    this.inspectShipSubject.next(ship);
  }

  get ship(): Ship {
    return this.inspectShipSubject.getValue();
  }
公共房间$:可见;
private inspectShipSubject:BehaviorSubject=new BehaviorSubject(空);
建造师(
...
) { }
恩戈尼尼特(){
this.rooms$=this.inspectShipSubject.switchMap(ship=>this.roomByShipService.getRoomsByShip(ship));
}
@输入()
设置船舶(船舶:船舶){
这个。检查ShipSubject。下一个(ship);
}
获取ship():ship{
返回此.inspectShipSubject.getValue();
}
以及模板:

<some-component *ngFor="let room of rooms | async" [room]="room"></some-component>
<some-component *ngFor="let room of (rooms | async)" [room]="room"></some-component>


能否尝试将表达式
(rooms | async)
放入括号中?尝试将this.rooms初始化从构造函数移动到ngOnInit()中@martin谢谢,我试过了,但没什么不同。我不确定哪个是正确的,因为许多示例都使用了这两种样式。相关:。异步管道已经添加了subscription@AndreiMatracaru谢谢,我尝试了上面的建议,没有发现任何区别。哦,你使用了
inspectShipSubject
…的主题我从名称:)中意识到了这一点。为了更好地理解行为主体的区别,请看一下@AndreiMatracaru,那么为什么它会在这里产生差异?请解释:)如果它是一个普通主体,并且在订阅之前发出一个值,订阅方将不会得到该值。它只会在订阅之后发出值bed。因此,在您的情况下,它可能在第一次更改发生之前不会被触发。主体仅在发出值时中继值。然而,BehaviorSubject额外存储“当前”值,并将该值发送给新订阅者。在构造BehaviorSubject时,您必须提供初始“当前”值(通常为空),就像你做的一样。ReplaySubject是你可以研究的另一个选项。但是我没有空间了