考虑 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]
}
这是模板:
<some-component *ngFor="let room of rooms | async" [room]="room"></some-component>
除非我取消注释 [1]
指示的行,否则它不起作用('foo' 未打印且无数据显示)。为什么模板不触发可观察对象自动执行?
有没有比使用空白订阅更好的方法?
最佳答案
好吧,我不确定为什么,但诀窍是在 this.inspectShipSubject
上使用 BehaviourSubject
而不是 Subject
。
这很好用,并由模板正确触发。
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();
}
和模板:
<some-component *ngFor="let room of (rooms | async)" [room]="room"></some-component>
关于javascript - Angular2 Observable 不是由异步管道触发的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45758211/