如何在valueChanges订阅中向数组中添加元素(Angular)



如果表单有效,我如何从响应式表单中获取值并将其设置为数组?在我的应用程序中,我有一个动态表单,不同的表单看起来是动态的。

getFormval(){
let arr = [];
this.form.valueChanges.pipe(
debounceTime(400)
)
.subscribe(_ => {
if (this.form.valid) {
// i would like to add form values to this arr array
arr.push(this.form.value);
}
})
// i want to get arr with all the values here
console.log(arr);
}

在处理可观察对象时,这是初学者常见的陷阱。浏览发布的代码…

getFormval(){
// the array is declared here
let arr = [];
// the subscription is declared here. 
// declaring a subscription does not immediately update the arr
// what happens inside the subscription occurs outside this function.
this.form.valueChanges.pipe(
// ignore any changes until 400ms have passed since the last change.
debounceTime(400)
)
.subscribe(_ => {
if (this.form.valid) {
// the array is updated after the line below runs
arr.push(this.form.value);
}
})
// the array is still [] here because this executes immediately
//   after the subscription is declared. 
console.log(arr);
}

因此,假设在启动订阅后立即发生值更改,则在arr中获得值之前至少需要400 ms。此时,该功能已完成[]arr的记录。

在不了解arr的使用的情况下,我不能确切地告诉你如何处理arr,但我可以告诉你,如果你在subscribe块中记录arr,你会看到它的值(提供if语句中的valid条件得到满足)

一个常见的模式是存储一个值作为valueChanges的响应,并在html中显示该值,看起来像这样:

<!-- myComponent.template.html -->
<div *ngFor="let val of arr">
{{val | json}}
</div>
// myComponent.component.ts
// Declare an `arr` to store the history of the form
arr: myFormType[] = []
ngOnInit() {
myForm.valueChanges.subscribe((val: myFormType) => {
// As the changes occur, they are pushed to the component's `arr` property
this.arr.push(val)
}
}

顺便说一句,subscribe的参数在这个例子中是表单值的函数,所以你可以写

....subscribe(value) => {
if(this.form.valid) {
arr.push(value)
}
}

最新更新