ค้นหาเว็บไซต์

angular - วิธีวนลูปผ่านอาร์เรย์ภายใน observable โดยใช้ async pipe?


ฉันกำลังใช้งาน API ซึ่งส่งผลลัพธ์ตอบกลับมาแบบนี้:

case:1
requests:[reqObj1,reqObj2,reqObj3]
count:3
message:"Found requests successfully."
pagesCount:1

บริการ:

listRequest(sort, records, pageNumber, queries?): Observable<any> {
    const updateQueries = this.gtn.getHeaders() as RequestOptions;
    updateQueries.params = queries;
    return this.http
      .get(globals.domain + '/team/requests/list/sortBy-' + sort + '/' + records + '/' + pageNumber + '/', updateQueries)
      .map(res => {
        this.responseData = res.json();
        return this.responseData;
      });
  }

นี่จะส่งค่ากลับเป็น Observable พร้อมกับวัตถุการตอบสนองตามที่กล่าวไว้ข้างต้น ฉันจะรับ observable นี้ในคอมโพเนนต์และกำหนดให้กับ observable ภายในคอมโพเนนต์

ส่วนประกอบ :

this.requestResponse= this.rts.listRequest(sort, records, page, this.q);

ฉันต้องการวนลูปผ่านอาร์เรย์ของคำขอซึ่งอยู่ใน observable และฉันกำลังใช้ async pipe ใน HTML ของฉัน

HTML :

    <div class="request-items-inner" *ngFor="let request of requestResponse.requests | async">
{{request.createdAt}}
</div>

แต่นี่ไม่ได้แสดงอะไรบนหน้าจอ และถ้าฉันใช้ *ngFor="let request of requestResponse | async" มันจะแสดงข้อผิดพลาดในคอนโซล

คำตอบ #1

คุณต้องแกะการตอบกลับด้วย pipe 'async' ก่อน จากนั้นจึงวนซ้ำในอาร์เรย์ requests

<div class="request-items-inner" *ngFor="let request of (requestResponse | async)?.requests">
  {{ request.createdAt }}
</div>