2
votes

I'm fairly new to Angular 4/ngrx and Rx so not quite sure what i'm doing wrong here. In my Effect I want to execute a search using my service. The method returns an Observable. Then I map that to return a new payload.

here is the code:

    @Effect() executeSearchEffect = this.actions.ofType(SEARCH_EXECUTE)
    .map((a: SearchExecuteAction) => {
        return this.searchService.doSearch(a.payload.search.searchText)
                   .map((r) => {
                        type: SEARCH_COMPLETE,
                        payload: a.payload   // just for testing,same as input!
                          }));
    });

In the above, doSearch returns an Observable. The error I get is Actions must have a type property which I am returning here.

if I change the code to simply as below it works without errors like a charm:

    @Effect() executeSearchEffect = this.actions.ofType(SEARCH_EXECUTE)
    .map((a: SearchExecuteAction) => {
        return {
               type: SEARCH_COMPLETE,
               payload: a.payload   // just for testing,same as input!
               });

What am I doing wrong here, how do I map the Observable from my service to dispatch a new action. Note, my Actions are just interfaces so I can't do a new SearchCompleteAction({}) etc.

2

2 Answers

3
votes

In your first code your aren't returning anything. Because (e) => { } just opens a scope and doesn't return an object. That's why your second code is working. You have to write return to return an object when using array functions.

Also you should really consider taking a look at the ngrx-example-app.

4
votes

Assuming searchService makes a http call to search , .map do not wait for the async call. You should use .flatMap .

  @Effect() executeSearchEffect = this.actions.ofType(SEARCH_EXECUTE)
    .flatMap((a: SearchExecuteAction) => 
        this.searchService.doSearch(a.payload.search.searchText)
                   .map((r) => ({
                        type: SEARCH_COMPLETE,
                        payload: a.payload   // just for testing,same as input!
                          })));
    );