简体   繁体   中英

rxjs and angular 2 and the use of the “take” operator

I am trying to use the "take" operator in my code (learning rxjs) but it is not sending the top 5 like I want. my simple code is below, anyone have any idea how to help?

countries: Observable<Country[]>;

private searchTerms = new Subject<string>();

this.countries = this.searchTerms.debounceTime(300).distinctUntilChanged().switchMap(  
            searchTerm => searchTerm ? this.countrySearchService.search(searchTerm) : observable.of<Country[]>([])) 
            .take(5);

After reading your comment, I understand you need the first 5 countries. Now note that your observable emits arrays of countries and not countries. The reason you use Observable.of instead of Observable.from. So, the right syntax should be:

this.countries = this.searchTerms.debounceTime(300).distinctUntilChanged().switchMap(  
        searchTerm => searchTerm ? this.countrySearchService.search(searchTerm) : observable.from<Country[]>([])) 
        .take(5);

If you want a sample that demonstrate various use cases, have a look at this jsbin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM