我试图实现一个Observables数组,它观察组织为JSON对象的输入。我有一个HTML文档,它可以(动态更改)多个输入以创建多个用户。为了评估输入,我打算在创建新的用户输入表单时将JSON对象推送到数组。有一次,我想提交,数组被评估然后提交。
我怎么做这个?
提前谢谢!
澄清:
HTML-模板:
<div class="item">
<input type="text" id="firstName1">
<input type="text" id="lastName1">
</div>
<button (click)="createUser()">
<button (click)="submit()">
角:
users = [];
constructor(private elRef:ElementRef) {}
createUser() {
//DeepClone of User Input
this.elRef.nativeElement.querySelector('.item').cloneNode(true);
let user = {
firstName: FIRSTNAME_OBSERVER,
lastName: LASTNAME_OBSERVER
}
/*
array that contains observables for each instance of .item
*/
this.users.push(user);
}
submit() {
// Submit Array with calculated items.
}
修改
const firstName = this.elRef.nativeElement.querySelector('#firstname').value;
const lastName = this.elRef.nativeElement.querySelector('#lastName').value;
const user = {
firstName: Observable.of(firstName),
lastName: Observable.of(lastName)
};
this.users.push(Observable.of(user));
Observable.forkJoin(this.users).subscribe( (res) => {
console.log(res);
});
答案 0 :(得分:0)
我认为您可以使用以下内容:
Observable.forkJoin([...observable1, observable2]).subscribe(res => {
// do some magic
res.forEach(item => {
this.user.push(item);
});
})
请参阅this reference。这将为您提供如何使用它的示例。
修改强>
对不起,也许我不太清楚我的建议,请尝试以下方法。
const firstName = this.elRef.nativeElement.querySelector('#firstname').value;
const lastName = this.elRef.nativeElement.querySelector('#lastName').value;
const userContant = {
firstName: firstName,
lastName: lastName
};
Observable.forkJoin([Observable.of(userContant )]).subscribe( (res) => {
res.forEach(item => {
this.user.push(item);
})
});
也许这种方式比你的方法更好:
HTML:
<div class="item">
<input type="text" [(ngModel)]="firstName">
<input type="text" [(ngModel)]="lastName">
</div>
<button (click)="createUser()">
<button (click)="submit()">
打字稿:
constructor(private elRef:ElementRef) {}
createUser() {
this.user.push({
firstName: this.firstName,
lastName: this.lastName
})
}
submit() {
// Submit Array with calculated items.
}