angular - ใช้ ngFor กับ async pipe เพื่อแสดงอาร์เรย์ของ observables
ฉันกำลังประสบปัญหาในการเข้าใจว่าทำไม ngFor ถึงไม่ทำงานกับอาเรย์ของ observables
export class DashboardComponent implements OnInit {
dwsubscriptions: Observable<Dwsubscription>[] = new Array();
ngOnInit() {
this.dwsubscriptions.push(
this.devicewiseService.getSubscription('Randomizer', '1', 3, 1, -1)
)
}
}
แล้ว html ของฉัน
<div *ngFor="let dwsubscription of dwsubscriptions | async">
<p>value: {{dwsubscription.params.data}}</p>
</div>
getSubscriptions กำลังส่งค่ากลับเป็น observable
getSubscription(device: string, variable: string, type: number, count:number, length:number): Observable<Dwsubscription> {
ฉันกำลังได้รับข้อผิดพลาด
ข้อผิดพลาด Error: InvalidPipeArgument: '[object Object]' สำหรับ pipe 'AsyncPipe'
สิ่งนี้ทำงานได้ดีหากฉันใช้ async pipe กับ observables ตัวเดียวที่ส่งกลับมาจาก getSubscription() ทำไมฉันถึงไม่สามารถผลัก observables เหล่านั้นไปยังอาเรย์แล้ววนซ้ำผ่านพวกมันในเทมเพลตของฉันโดยใช้ ngFor ได้?
คำตอบ #1
คุณกำลังสร้างอาร์เรย์ของ observable คุณจะต้องวนลูปผ่านแต่ละ observable แล้วจากนั้นใช้ async pipe กับแต่ละตัว
ลองอันนี้:
<div *ngFor="let dwsubscription of dwsubscriptions">
<div *ngIf="dwsubscription | async as dw">
<p>value: {{dw.params.data}}</p>
</div>
</div>
คำตอบ #2
คำถามของคุณสื่อว่าคุณต้องการอาเรย์ของ Observables ซึ่งหมายความว่าคุณจะต้องแก้ไขวิธีที่คุณอ้างอิง dwsubscriptions ใน HTML ของคุณ dwsubscriptions ไม่ใช่ Observable ในตัวอย่างของคุณ มันเป็นอาเรย์ของ Observables ดังนั้นจึงไม่จำเป็นต้องใช้ async pipe กับ dwsubscriptions
นี่คือตัวอย่าง Stackblitz แบบรวดเร็ว
โซ่มาจาก:
<ul>
<li *ngFor="let obs of dwsubscriptions">
{{obs | async | json}}
</li>
</ul>
