Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combineLatest with FormControl valueChanges event binding not emitting

I listen to 2 forms via 2 [formControl] "toppings":array and "toppings2":array.

I must have the 2 values of the forms in the same time. So i combine my two observables with "CombineLatest"

My code:

ngOnInit() {
combineLatest(this.toppings.valueChanges, this.toppings2.valueChanges)
    .subscribe(val => console.log(val)) 
}

But now, in the initialisation of the component, only one form send console.log(val).

If i click on this form, after i receive log of my second form. Have you meet this problem ?

like image 615
Newbiiiie Avatar asked Sep 05 '18 09:09

Newbiiiie


1 Answers

You probably want to have an initial value for both Observables. combineLatest will only emit if all Observables have emitted at least one value. Use the startWith operator to create this behaviour, like this:

combineLatest(
    this.toppings.valueChanges.pipe(startWith("")), 
    this.toppings2.valueChanges.pipe(startWith("")))

Or, if you have initial values available, like suggested:

combineLatest(
    this.toppings.valueChanges.pipe(startWith(this.toppings.value)), 
    this.toppings2.valueChanges.pipe(startWith(this.toppings2.value)))

Note, that this will emit once with the initial values. To supress this behaviour, you can use the skip(1) operator to ignore this initial notification.

like image 121
ggradnig Avatar answered Nov 05 '22 04:11

ggradnig