Angular NgRx技术问询:如何在Effect中获取ofType指定动作的参数并传递给服务方法
Answer
Absolutely! You can easily access the keywords parameter from your filterArticles action and pass it to getFilteredCardInfo—here's how to adjust your Effect code:
Updated Effect Code
filterArticles$ = createEffect(() => this.actions$.pipe( ofType(filterArticles), // Capture the action instance to access its keywords property switchMap((action) => from(this.cardService.getFilteredCardInfo(action.keywords)).pipe( map(articles => loadArticlesSuccess({ articles: articles })), catchError(error => of(loadArticlesFailure({ error }))) )) ));
Key Changes Explained
- Access the action payload: When you use
ofType(filterArticles), the stream emits the actualfilterArticlesaction object. By adding(action)insideswitchMap, you can access its properties—includingkeywords. - Pass keywords to the service: Replace the empty string
''withaction.keywordsto send the user's input directly togetFilteredCardInfo.
Quick Check: Ensure Your Action is Defined Correctly
Make sure your filterArticles action creator is set up to accept the keywords parameter, like this:
import { createAction, props } from '@ngrx/store'; export const filterArticles = createAction( '[Articles] Filter Articles', props<{ keywords: string }>() // This defines the payload structure );
That's it! Now when filterArticles is dispatched with a keywords value, your Effect will pick it up and use it to filter your articles via the service.
内容的提问来源于stack exchange,提问作者Yaroslav Omelianenko
相关产品推荐
相关产品推荐

