以下是解决同一问题的两种方法,即对用户在文本框中输入的某些字符进行响应式搜索。第一个解决方案来自ngrx 示例,第二个解决方案来自egghead即时搜索课程。
- 第一个解决方案使用
Observable
,而第二个使用Subject
. - 该
Observable
解决方案takeUntil
只调用一次服务器。该Subject
解决方案使用distinctUntilChanged
.
有人可以解释这两种方法的优缺点吗?
使用 Observable 搜索:
@Injectable()
export class BookEffects {
@Effect()
search$: Observable<Action> = this.actions$
.ofType(book.ActionTypes.SEARCH)
.debounceTime(300)
.map(toPayload)
.switchMap(query => {
if (query === '') {
return empty();
}
const nextSearch$ = this.actions$.ofType(book.ActionTypes.SEARCH).skip(1);
return this.googleBooks.searchBooks(query)
.takeUntil(nextSearch$)
.map(books => new book.SearchCompleteAction(books))
.catch(() => of(new book.SearchCompleteAction([])));
});
constructor(private actions$: Actions, private googleBooks: GoogleBooksService) { }
}
@Component({
selector: 'bc-find-book-page',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<bc-book-search [query]="searchQuery$ | async" [searching]="loading$ | async" (search)="search($event)"></bc-book-search>
<bc-book-preview-list [books]="books$ | async"></bc-book-preview-list>
`
})
export class FindBookPageComponent {
searchQuery$: Observable<string>;
books$: Observable<Book[]>;
loading$: Observable<boolean>;
constructor(private store: Store<fromRoot.State>) {
this.searchQuery$ = store.select(fromRoot.getSearchQuery).take(1);
this.books$ = store.select(fromRoot.getSearchResults);
this.loading$ = store.select(fromRoot.getSearchLoading);
}
search(query: string) {
this.store.dispatch(new book.SearchAction(query));
}
}
使用主题搜索:
import { Component } from '@angular/core';
import { WikipediaSearchService } from './wikipedia-search.service';
import { Subject } from 'rxjs/Subject';
//application wide shared Rx operators
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
items:Array<string>;
term$ = new Subject<string>();
constructor(private service:WikipediaSearchService) {
this.term$
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.service.search(term))
.subscribe(results => this.items = results);
}
}
<div>
<h2>Wikipedia Search</h2>
<input (input)="term$.next($event.target.value)">
<ul>
<li *ngFor="let item of items">{{item}}</li>
</ul>
</div>