angular - 如何从 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 中工作正常,但我不知道如何在打字稿中做到这一点。
谢谢你帮助我。
解决方案
您需要订阅 observable,以便当有一个值传递时,您能够接收它并使用它做一些事情。大概是这样的:
this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
this.product$.subscribe(valueFromSubscription => this.product.patchValue(...));
推荐阅读
- c - 扫描字符并在 C 中打印的问题
- java - 如何处理Android中的意外响应500
- java - Springfox Swagger vs Swagger maven插件
- python-3.x - Python 和 tkinter:类内的事件处理
- python-3.x - Python中低频词的快速去除
- python-3.x - 每当我在 Vispy 中创建画布时,Spyder iPython 窗口中都会出现警告
- ruby-on-rails - 如何在停产的私有资源页面上测试预期的 404 响应?
- javascript - 如何根据输入值及其概率计算最可能的输出?
- scala - 确保我的 trait 的类型参数是 Monad
- python - 未找到没有参数的“detailed_view”反向