首页 > 解决方案 > 如何从 Observable 设置默认表单值?

问题描述

这是我的 ts 组件

export interface Product{
    id?:string,
    name:string,
    price:string;
    quantity:string;
    tags:Tags[];
    description:string;
    files: File[];
}

product$:Observable<Product | undefined>;

ngOnInit(): void { 
  this.store.dispatch(new productActions.LoadProduct(fromProduct.getCurrentProductId.toString()));
  this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
}

最后和第二个语句收集了产品可观察的价值并且工作正常。

this.product = this.fb.group({
    name:['',[
      Validators.required,
      Validators.minLength(1),
      Validators.maxLength(128)
    ]],
    price:['',
    Validators.required],
    tags:this.fb.array(this.tags),
    quantity:['',Validators.required],
    description:['',
    Validators.required]
  });
}

现在我想要的是从 Product$ (observable) 设置 Form 的默认值

上面的代码设置了 name '' 的默认值。但我想从 (product$ | async).name----->> 设置一个默认值,这在 Html 中工作正常,但我不知道如何在打字稿中做到这一点。

谢谢你帮助我。

标签: angulartypescriptobservableangular-reactive-forms

解决方案


您需要订阅 observable,以便当有一个值传递时,您能够接收它并使用它做一些事情。大概是这样的:

this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
this.product$.subscribe(valueFromSubscription => this.product.patchValue(...));

推荐阅读