I'm learning Angular 5 with Typescript. I'm trying to implement an angular material autocomplete and I've found the following code which is very obscur to me :
this.filteredStates = this.stateCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this.filterStates(state) : this.states.slice())
);
The full code can be found here : https://stackblitz.com/angular/mdokmnyajmd?file=app%2Fautocomplete-overview-example.ts
I tend to think that when a changed occurs on stateCtrl, then it returns the filterStates(state) result if and only if a concrete element has been selected in autocomplete.
What I don't understand is the use of startWith('') ?! Why not simpling call subscribe on valueChanges ?
startWith(... values: D[]): OperatorFunction<T, T | D> Returns an observable that, at the moment of subscription, will synchronously emit all values provided to this operator, then subscribe to the source and mirror all of its emissions to subscribers.
RxNet StartWith Rx.NET implements this operator as StartWith . It accepts an array of items which it prepends to the resulting Observable sequence in the order they appear in the array before it emits the items from the source Observable.
valueChanges
will not emit any values initially (until state actually changes). When you need to calculate something from initial state you use startWith
to make observable emit a value even though it wouldn't normally.
If you want to process initial value without startWith
, you can create another stream
Observable.of(stateCtrl.value).pipe(
map(state => state ? this.filterStates(state) : this.states.slice())
);
which will emit only one value. But it's easier to handle both cases at the same time, so startWith
is a good way to do it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With