Reputation: 117
My hotel.service.ts
getRoomList(): Observable<RoomListType[]> {
return this.http.get<RoomListType[]>('http://localhost:3001/rooms');
}
my content.ts is
get roomList$() {
return this.hotelService.getRoomList().pipe(shareReplay(1));
}
my content.html is
<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>
My goal is I want to bind hotel rooms in my html file. I read some article on stackoverflow to use shareReplay(1) but I didnt work for me. How can I achieve this.
Upvotes: 0
Views: 711
Reputation: 2324
You've created an infinite loop by triggering an http request inside that getter.
When change detection occurs, your getter will be called. Your getter then makes an http request, which triggers change detection, which calls your getter, etc.
The roomList$
Observable you're passing to the async pipe should be created once, probably in ngOnInit
.
So your content.ts
would look something like this:
roomList$: Observable<RoomListType[]>;
ngOnInit() {
this.roomList$ = this.hotelService.getRoomList();
}
shareReplay doesn't seem necessary in your situation—that's used if you might have late subscribers to your Observable who should receive the last emitted value immediately upon subscription rather than having to wait for the Observable to emit again.
And if you did have that situation, you would configure it more like this:
getRoomList() {
return this.roomList$.pipe(shareReplay(1));
}
rather than with a getter that triggers a new http request every time it's referenced.
Here's a StackBlitz with your basic scenario not triggering an infinite loop.
Upvotes: 2