首页 > 解决方案 > Angular 异步管道是如何工作的

问题描述

我正在开发一个 Angular 应用程序。问题是我的模板annonces在相应组件中对变量 ( ) 的请求返回其值之前显示。所以我必须使用async管道。我尝试使用它,但模板中的变量没有刷新,并且我没有*ngFor指令的结果

这是组件

export class AppListProduitImmobilierComponent implements OnInit {

  public annonces: Observable<ProduitImmobilierDTO[]>
.................
.................
  ngOnInit() {
    this.preloadData();  // this function does a pre-request and afterwards call loadData(search)
................
...............
    loadData(search: Search) {
      this.annonces = this.service.getListProduitImmobilierDTO(this.pagesize, this.page, search);

模板部分如下:

<mat-card *ngFor="let annonce of annonces | async; let i = index" class="pointer">

服务如下:

  getListProduitImmobilierDTO(pagesize: number, page: number, search: Search): Observable<ProduitImmobilierDTO[]> {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    const options = { headers: headers };
    search.page = page;
    search.pageSize = pagesize;
    return this.http.post<Search>('/api/produitimmobilier/all', JSON.stringify(search), options).pipe(map((search: Search) => search.result as ProduitImmobilierDTO[]));
  }

标签: angulartypescriptasync-pipe

解决方案


由于我的 POST 请求有效(没有异步管道),我尝试从请求的结果中构建一个 observable 并在模板中使用它

在我的组件中:

public annonces$: Observable<ProduitImmobilierDTO[]> = new Observable<ProduitImmobilierDTO[]>();

    loadData(search: Search) {
      this.service.getListProduitImmobilierDTO(this.pageSize, this.page, search).subscribe(
        articles => {this.annonces = articles; 
          this.annonces$ = of(articles);
          this.collectionSize = articles[0].collectionSize; console.log('this.annonces'); console.log(this.annonces)},
        (err: HttpErrorResponse) => {
          console.log(err);
        }
      );
    }

并且在模板中

<mat-card *ngFor="let annonce of annonces$ | async; let i = index" class="pointer">

但它不起作用


推荐阅读