繁体   English   中英

ngIf: ngIf 模板中的异步

[英]ngIf: async inside ngIf template

Angular:11.0.2(显示我的问题的简化示例)

我在ngIf模板中使用async pipe 时遇到一些问题(我的数据没有很好地刷新)。 我写了一个简单的例子来暴露我的问题。

Plunker 代码在这里

重现步骤:

  • 多次点击add
  • 点击toggle
  • data$ | async data$ | async显示defaultValue而不是myArray值(不是预期的)
  • 点击add
  • data$ | async data$ | async被刷新并显示myArray值(预期
  • 点击 2 次toggle
  • data$ | async data$ | async再次显示defaultValue不是预期的)

看起来 ngIf 将 data$ 初始值存储在第一个 ngOnInit 上。 为什么{{data$ | async | json}} {{data$ | async | json}} {{data$ | async | json}}在切换ngIf块时返回myArray的默认值(即使myArray已更改)。

如何使用rxjsngIf处理这种情况?

模板:

<button (click)="add()">+ add</button>
<button (click)="sub()">- sub</button>
<button (click)="toggle()">toggle</button>

myArray={{myArray.value | json}}
length={{myArray.length}}

<div *ngIf="showMe">
  Inside ngIf:<br>
  data={{data$ | async | json}}<br>
  myArray={{myArray.value | json}}
</div>

零件:

import { Component, OnInit,ChangeDetectorRef } from "@angular/core";
import { FormArray, FormBuilder } from "@angular/forms";
import {  combineLatest, Observable, of  } from "rxjs";
import { filter, map, startWith, tap } from 'rxjs/operators';
@Component({
  selector: "my-app",
  templateUrl: "src/app.component.html"
})
export class AppComponent implements OnInit{

  showMe = false;
  form: FormGroup;
  x: number = 0;
  data$: Observable<any>;

  constructor(
    private fb: FormBuilder,
    private cd: ChangeDetectorRef
  ) {}

  ngOnInit() {
    
    this.form = this.fb.group({
      myArray: this.fb.array(['defaultValue'])
    }) ;

    this.data$ = this.myArray.valueChanges.pipe(startWith(this.myArray.value));
  }

  add() {
    this.myArray.push(this.fb.control(this.x++));
  }

  sub() {
    this.myArray.removeAt(this.myArray.length - 1);
  }

  toggle() {
    this.showMe = !this.showMe;
  }

  get myArray(): FormArray {
    return this.form.get('myArray') as FormArray;
  }
}

使用defer它将为每个新订阅者生成一个实际值。

 this.data$ = defer(() =>
      this.myArray.valueChanges.pipe(startWith(this.myArray.value))
  );

分叉的工作示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM