|
| 1 | +// #docplaster |
| 2 | +// #docregion |
| 3 | +import 'dart:async'; |
| 4 | + |
| 5 | +import 'package:angular2/core.dart'; |
| 6 | +import 'package:angular2/router.dart'; |
| 7 | +import 'package:stream_transformers/stream_transformers.dart'; |
| 8 | + |
| 9 | +import 'hero_search_service.dart'; |
| 10 | +import 'hero.dart'; |
| 11 | + |
| 12 | +@Component( |
| 13 | + selector: 'hero-search', |
| 14 | + templateUrl: 'hero_search_component.html', |
| 15 | + styleUrls: const ['hero_search_component.css'], |
| 16 | + providers: const [HeroSearchService]) |
| 17 | +class HeroSearchComponent implements OnInit { |
| 18 | + HeroSearchService _heroSearchService; |
| 19 | + Router _router; |
| 20 | + |
| 21 | + // #docregion search |
| 22 | + Stream<List<Hero>> heroes; |
| 23 | + // #enddocregion search |
| 24 | + // #docregion searchTerms |
| 25 | + StreamController<String> _searchTerms = |
| 26 | + new StreamController<String>.broadcast(); |
| 27 | + // #enddocregion searchTerms |
| 28 | + |
| 29 | + HeroSearchComponent(this._heroSearchService, this._router) {} |
| 30 | + // #docregion searchTerms |
| 31 | + |
| 32 | + // Push a search term into the stream. |
| 33 | + void search(String term) => _searchTerms.add(term); |
| 34 | + // #enddocregion searchTerms |
| 35 | + // #docregion search |
| 36 | + |
| 37 | + Future<Null> ngOnInit() async { |
| 38 | + heroes = _searchTerms.stream |
| 39 | + .transform(new Debounce(new Duration(milliseconds: 300))) |
| 40 | + .distinct() |
| 41 | + .transform(new FlatMapLatest((term) => term.isEmpty |
| 42 | + ? new Stream<List<Hero>>.fromIterable([<Hero>[]]) |
| 43 | + : _heroSearchService.search(term).asStream())) |
| 44 | + .handleError((e) { |
| 45 | + print(e); // for demo purposes only |
| 46 | + }); |
| 47 | + } |
| 48 | + // #enddocregion search |
| 49 | + |
| 50 | + void gotoDetail(Hero hero) { |
| 51 | + var link = [ |
| 52 | + 'HeroDetail', |
| 53 | + {'id': hero.id.toString()} |
| 54 | + ]; |
| 55 | + _router.navigate(link); |
| 56 | + } |
| 57 | +} |
0 commit comments