0

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.

1
  • Can you show us the result of the HTTP request? According to your template, it should be an array. You don't need the shareReplay operator for this. Also, I would recommend moving your HTTP request out of the getter which is most likely giving you problems, move it to your ngOnInit instead. Commented Sep 14, 2020 at 21:11

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome! I hope it helps. If you find that it answers your question, please accept it as the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.