最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular2: how to initially trigger Control.valueChanges - Stack Overflow

programmeradmin1浏览0评论
constructor(private _service: LocatorService) {
    this.counties = this.countyTerm.valueChanges
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap((term: string) => _service.getCounties(term));
}
counties: Observable<County[]>;
countyTerm = new Control();

As expected, this.counties is only populated once a value is entered into the countyTerm bound control.

How can I trigger valueChanges when this ponent is instantiated so that the set of counties is loaded initially?

I tried the following, but it had no effect (implements OnInit was added to the class):

ngOnInit() {
    this.countyTerm.updateValue('', { emitEvent: true });
}
constructor(private _service: LocatorService) {
    this.counties = this.countyTerm.valueChanges
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap((term: string) => _service.getCounties(term));
}
counties: Observable<County[]>;
countyTerm = new Control();

As expected, this.counties is only populated once a value is entered into the countyTerm bound control.

How can I trigger valueChanges when this ponent is instantiated so that the set of counties is loaded initially?

I tried the following, but it had no effect (implements OnInit was added to the class):

ngOnInit() {
    this.countyTerm.updateValue('', { emitEvent: true });
}
Share Improve this question edited Nov 9, 2021 at 13:15 Ruli 2,79113 gold badges33 silver badges47 bronze badges asked Mar 18, 2016 at 4:11 gxclarkegxclarke 1,9733 gold badges21 silver badges42 bronze badges 2
  • You van give it a default value countyTerm = new Control('Default value'); – Eric Martinez Commented Mar 18, 2016 at 4:15
  • That does give the control a default value, but it still doesn't trigger valueChanges. – gxclarke Commented Mar 18, 2016 at 4:26
Add a ment  | 

3 Answers 3

Reset to default 4

Just start your stream out with a fixed value. Something like this:

this.counties = Rx.Observable.of('')
        .concat(this.countyTerm.valueChanges.debounceTime(300))
        .distinctUntilChanged()
        .switchMap((term: string) => _service.getCounties(term));

Use startWith RxJS operator to emit something before stream.

this.counties = this.countyTerm.valueChanges
    .startwith('')
    .debounceTime(300)
    .distinctUntilChanged()
    .switchMap((term: string) => _service.getCounties(term));

http://reactivex.io/documentation/operators/startwith.html

With RxJS 6 / 7 new syntax:

this.counties$ = this.countyTerm.valueChanges.pipe(
      startWith(''),
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((term: string) => _service.getCounties(term))
);
发布评论

评论列表(0)

  1. 暂无评论