我的hotel.service.ts
getRoomList(): Observable<RoomListType[]> {
return this.http.get<RoomListType[]>('http://localhost:3001/rooms');
}
我的content.ts是
get roomList$() {
return this.hotelService.getRoomList().pipe(shareReplay(1));
}
我的content.html是
<div class="col-md-9" *ngFor="let item of (roomList$ | async)">
<div class="row">
<div class="col-md-4">{{ item.RoomType }}</div>
<div class="col-md-8 d-flex justify-content-end">
<button class="ml-1 btn btn-outline-danger btn-sm" (click)="openScrollableContent(longContent)"><i class="fa fa-bed"></i>Oda Özellikleri</button>
</div>
</div>
...
</div>
我的目标是我想在html文件中绑定酒店房间。我读了一些有关stackoverflow的文章以使用shareReplay(1),但我没有为我工作。我该怎么做到。
答案 0 :(得分:1)
您已经通过在该getter中触发一个http请求来创建无限循环。
发生更改检测时,将调用您的吸气剂。然后,您的getter发出一个http请求,该请求会触发更改检测,调用getter等。
您传递给异步管道的roomList$
可见对象应该创建一次,可能在ngOnInit
中创建。
所以您的content.ts
看起来像这样:
roomList$: Observable<RoomListType[]>;
ngOnInit() {
this.roomList$ = this.hotelService.getRoomList();
}
shareReplay在您的情况下似乎不是必需的-如果您的Observable订户可能较晚,则该订户应在订阅后立即收到最后一个发出的值,而不必等到Observable再次发出,则可以使用。
如果确实有这种情况,您可以像这样配置它:
getRoomList() {
return this.roomList$.pipe(shareReplay(1));
}
而不是使用getter每次引用都会触发一个新的http请求。
Here's a StackBlitz,并且基本情况为不触发无限循环。