如何在新的 Angular 17 中使用带有数组的异步管道?

问题描述 投票:0回答:1

假设我的组件类中有这个承诺。

testAsyncNumber = new Promise(
  (res,rej)=>{
    setTimeout(()=>{res([1,2,3,4,5])
  },2000);
});

在视图模板中,我需要使用异步管道获取数据。我尝试了以下方法。

<div>
  @for (number of (testAsyncNumber | async); track number) {
    {{ number }}
  } @empty {
    Empty list of users
  }
</div> 

但这行不通。如何克服这个问题?

angular angular-pipe angular17 async-pipe
1个回答
0
投票

您可以使用

from
运算符将 Promise 转换为可观察的!

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { from, merge, Observable, of } from 'rxjs';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
   <div>
    @for (number of (testAsyncNumber | async); track number) {
        {{ number }}
      } @empty {
        Empty list of users
      } 
</div> 
{{testAsyncNumber | async | json}}
  `,
})
export class App {
  testAsyncNumber: Observable<Array<number>> = merge(
    of([]),
    from(
      new Promise<Array<number>>((res, rej): void => {
        setTimeout(() => {
          res([1, 2, 3, 4, 5]);
        }, 2000);
      })
    )
  );
}

bootstrapApplication(App);
© www.soinside.com 2019 - 2024. All rights reserved.