簡體   English   中英

Angular 2 無限循環異步管道

[英]Angular 2 Endless loop async pipe

我的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) 但我沒有為我工作。 我怎樣才能做到這一點。

您已經通過在該 getter 中觸發 http 請求創建了一個無限循環。

當發生變化檢測時,您的 getter 將被調用。 然后您的 getter 發出一個 http 請求,這會觸發更改檢測,從而調用您的 getter 等。

您傳遞給異步管道的roomList$ Observable 應該創建一次,可能在ngOnInit

所以你的content.ts看起來像這樣:

roomList$: Observable<RoomListType[]>;

ngOnInit() {
  this.roomList$ = this.hotelService.getRoomList();
}

shareReplay在您的情況下似乎沒有必要 - 如果您的 Observable 可能有延遲訂閱者,他們應該在訂閱后立即接收最后發出的值,而不必等待 Observable 再次發出,則使用這種方法。

如果你確實遇到過這種情況,你會更像這樣配置它:

getRoomList() {
  return this.roomList$.pipe(shareReplay(1));
}

而不是每次引用時都會觸發新的 http 請求的 getter。

這是一個 StackBlitz ,您的基本場景不會觸發無限循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM