问题
I have a if
control statement in an effect to return an action in the case of data has been retrieved from a service, if not return another action to get data from another Web API
. It is a chained effects operation where there is another effect to handle the LOADFROMWEBAPI
action.
Is there a better way and avoid the if
control statement, and return one action like LoadFromWebAPI
only? Where the action SearchCompleteAction
can be returned is the question - in effect or reducer?
@Effect()
search$: Observable<Action> = this.actions$
.ofType(book.SEARCH)
.debounceTime(300)
.map(toPayload)
.switchMap(query => {
if (query === '') {
return empty();
}
const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);
return this.googleBooks.searchBooks(query)
.takeUntil(nextSearch$)
.map(books => {
if (data === undefined) {
return new book.LoadFromWebAPI(query);
} else {
return new book.SearchCompleteAction(books);
}
})
.catch(() => of(new book.SearchCompleteAction([])));
});
回答1:
@Effect()
search$: Observable<Action> = this.actions$
.ofType(book.SEARCH)
.debounceTime(300)
.map(toPayload)
.filter(query => query !== '')
.switchMap(query => {
const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);
return this.googleBooks.searchBooks(query)
.takeUntil(nextSearch$)
.map(books => data === undefined ? new book.LoadFromWebAPI(query) : new book.SearchCompleteAction(books))
.catch(() => of(new book.SearchCompleteAction([])));
});
来源:https://stackoverflow.com/questions/43597070/how-to-refactor-to-remove-the-control-statements-from-ngrx-effects