简体   繁体   English

Angular2 Observable不是由异步管道触发的

[英]Angular2 Observable isn't triggered by async pipe

Consider this simple snippet of angular2/rxjs/typescript 考虑一下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]
  }

Here's the template: 这是模板:

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

It doesn't work ('foo' is not printed and no data shows) unless I uncomment the line indicated [1] . 它不起作用('foo'没有打印,没有数据显示),除非我取消注释指示的行[1] Why doesn't the template trigger the observable to execute automatically? 为什么模板不会触发observable自动执行?

Is there a better way than to use a blank subscribe? 有没有比使用空白订阅更好的方法?

OK, I'm not sure why, but the trick is to use BehaviourSubject instead of Subject on this.inspectShipSubject . 好吧,我不知道为什么,但诀窍是在this.inspectShipSubject上使用BehaviourSubject而不是Subject

This works nicely and is triggered properly by the template. 这很好用,并由模板正确触发。

  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();
  }

And the template: 和模板:

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

I'm not sure if this is a good solution (or just a workaround), but you could store every event in an array and then loop the array: 我不确定这是一个很好的解决方案(或只是一种解决方法),但您可以将每个事件存储在一个数组中,然后循环该数组:

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

Edit: I have just realized that I'm not sure if you want to show a list of rooms or just the latest received room. 编辑:我刚刚意识到我不确定你是想要显示房间列表还是只显示最新收到的房间。 In case you just need the latest one, then I think you don't need a ngFor directive. 如果您只需要最新版本,那么我认为您不需要ngFor指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM