Marksman
Marksman

Reputation: 125

How to set initial observable value in Angularjs2?

export class RulesComponent {
  items: Observable<Array<string>>;
  term = new FormControl();

  constructor(private searchService: SearchService) {}

  ngOnInit() {
    this.items = this.term.valueChanges
      .debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchService.search('rules', term));
  }
}

@Injectable()
export class SearchService {

  constructor(private jsonp: Jsonp) {}

  search(name: string, term: string) {
    var search = new URLSearchParams();
    search.set('search', term);
    return this.jsonp
                .get('http://127.0.0.1:8000' , { search })
                .map(this.extractData)
                .json();
  }
}

I want search() to be called before term value changes and set items value to search result while page is loading, but I can't figure out how.

Upvotes: 2

Views: 3560

Answers (3)

Jan Cejka
Jan Cejka

Reputation: 331

Old question but today I was solving the same issue. Correct solution is:

ngOnInit() {
    this.items = this.term.valueChanges
      .startWith('')
      .debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchService.search('rules', term));
    this.term.setValue('search text here', {emitEvent:true});
}

Important is .startWith(initialValue) part that will emit initial value for observable. More is described in ReactiveX documentation

Upvotes: 3

Yakov Fain
Yakov Fain

Reputation: 12378

Try this:

this.term.setValue("New York");

Upvotes: 0

cDecker32
cDecker32

Reputation: 811

You should be able to trigger the search in the ngOnInit() function of the component like this.

ngOnInit() {
    this.items = this.term.valueChanges
      .debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchService.search('rules', term));
    this.term.setValue('search text here', {emitEvent:true});
}

Link to A2 FormControl documentation for reference: https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

Upvotes: 0

Related Questions