繁体   English   中英

Angular - 反应形式 valueChanges。 避免嵌套订阅

[英]Angular - Reactive form valueChanges. Avoid nested subscriptions

问题

所以。 我正在尝试使用会发生很大变化的异步数据预先填充反应式表单。 asyncData$ 从AppComponent馈送到处理表单的子组件 - FormComponent中的@input()

dataForm$tap()运算符中订阅是我可以使valueChanges工作并实际发出值的唯一方法,但是嵌套订阅是不行的,所以我想找到一个更好/更清洁的解决方案来避免这种情况 - 最好通过使用可观察的。 可能只是我遗漏了一些明显的东西

有人有建议吗?

表单本身必须是可观察的


应用组件

<div>
  <app-form [asyncData]="asyncData$ | async"></app-form>
</div>
export class AppComponent implements OnInit {
  title = 'observableForm';

  asyncData$: ReplaySubject<Data> = new ReplaySubject<Data>(1);

  ngOnInit(): void {
    setTimeout(() => this.asyncData$.next( {
      id: 42,
      name: 'Han Solo',
      heShotFirst: true
    } as Data), 2000);
  }
}

表单组件

<div *ngIf="(dataForm$ | async) as dataForm">
    <form [formGroup]="dataForm" style="padding: 5rem; display: grid; place-items: center;">
        <div>
            <label>
                Id
                <input type="text" [formControlName]="'id'">
            </label>
            <label>
                Name
                <input type="text" [formControlName]="'name'">
            </label>
            <br>
            <label>
                He shot first
                <input type="radio" [value]="true" [formControlName]="'heShotFirst'">
            </label>         
            <label>
                He did not
                <input type="radio" [value]="false" [formControlName]="'heShotFirst'">
            </label>         
        </div>
    </form>
    <div *ngIf="(lies$ | async) === false" style="display: grid; place-items: center;">
        <h1>I Must Not Tell Lies</h1>
    </div>
</div>
export class FormComponent implements OnInit, OnDestroy {
  @Input() set asyncData(data: Data) { this._asyncData$.next(data); }
  _asyncData$: ReplaySubject<Data> = new ReplaySubject<Data>(1);

  dataForm$: Observable<FormGroup>;
  valueChangesSub$: Subscription;

  lies$: Subject<boolean> = new Subject<boolean>();

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.dataForm$ = this._asyncData$.pipe(
      map(data => {
        return this.fb.group({
          id: [data?.id],
          name: [data?.name],
          heShotFirst: [data?.heShotFirst]
        });
      }),
      tap(form => {
            if (this.valueChangesSub$ != null) {
              this.valueChangesSub$.unsubscribe();
            }
            return form.valueChanges.subscribe(changes => {
              console.log(changes)
              this.lies$.next(changes.heShotFirst);
            });
          })
    );
  }

  ngOnDestroy(): void {
    this.valueChangesSub$.unsubscribe();
  }
}

我不确定为什么表单需要成为 Observable。 我改为使用OnChanges来监视来自父组件的更改,并使用valueChanges来监视表单的更改。

这是生成的代码:

import { Component, Input, OnInit, OnDestroy, OnChanges, SimpleChanges } from "@angular/core";
import { ReplaySubject, Observable, Subscription, Subject } from "rxjs";
import { Data } from "./data";
import { FormGroup, FormBuilder } from "@angular/forms";
import { map, tap } from "rxjs/operators";

@Component({
  selector: "app-form",
  templateUrl: "./form.component.html"
})
export class FormComponent implements OnInit, OnDestroy, OnChanges {
  @Input() asyncData: Data;

  dataForm$: Observable<FormGroup>;
  dataForm: FormGroup;
  valueChangesSub: Subscription;

  lies$: Subject<boolean> = new Subject<boolean>();

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.dataForm = this.fb.group({
      id: "",
      name: "",
      heShotFirst: false
    });

    this.valueChangesSub = this.dataForm.valueChanges.subscribe(changes => {
      console.log(changes);
      this.lies$.next(changes.heShotFirst);
    });
  }

  ngOnChanges(changes: SimpleChanges) {
    let currentValue: Data = changes.asyncData.currentValue;
    console.log("changes", currentValue);

    if (currentValue !== null) {
      this.dataForm.patchValue({
        id: currentValue.id,
        name: currentValue.name,
        heShotFirst: currentValue.heShotFirst
      });
    }
  }

  ngOnDestroy(): void {
    this.valueChangesSub.unsubscribe();
  }
}

我在这里有一个stackblitz: https://stackblitz.com/edit/angular-async-form-deborahk

使用OnChanges ,每次将新值发送到父组件的 stream 时,子组件都会收到通知。 (我试图通过在父组件中设置第二个setTimeout来模拟它。)

然后表单上的valueChanges似乎按预期工作。

如果这不是您想要的,请随时 fork stackblitz 并根据需要对其进行修改以演示您的问题。

设置两个 Observables 怎么样?

this.dataForm$ = this._asyncData$.pipe(
  map(data => this.fb.group({
    id: [data?.id],
    name: [data?.name],
    heShotFirst: [data?.heShotFirst]
  })),
);
this.lies$ = this.dataForm$.pipe(
  switchMap(form => form.valueChanges),
  map(changes => changes.heShotFirst),
);

暂无
暂无

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

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