DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • JSON-Based Serialized LOB Pattern
  • Rust’s Ownership and Borrowing Enforce Memory Safety
  • Mule 4 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • High-Performance Java Serialization to Different Formats

Trending

  • Building a Skill-Based Agentic Reviewer with Claude Code: A Practical Guide Using Skills.MD, MCP Servers, Tools, and Tasks
  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  • RAG Is Not Enough: Advanced Retrieval Architectures Using Vertex AI Search on GCP
  • Leveraging Apache Flink Dashboard for Real-Time Data Processing in AWS Apache Flink Managed Service
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Use State Inside of an Effect Component With ngrx

How to Use State Inside of an Effect Component With ngrx

By 
Javier Santos user avatar
Javier Santos
·
Apr. 24, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
19.5K Views

Join the DZone community and get the full member experience.

Join For Free

For this post, I assume you already have knowledge about ngrx (a reactive state management framework for Angular), and you are working with reducers, actions, effects, and selector components. You can find information in ngrx. Today, I want to show you how to work with state inside of the effect component.

TypeScript
 




xxxxxxxxxx
1
18


 
1
@Injectable()
2
export class AppEffects {
3
4
  constructor(private actions: Actions, private service: yourService) {}
5
6
   infoEffect = 
7
    createEffect(() => 
8
        this.actions.pipe(
9
            ofType(getInfoAction),
10
            mergeMap(() =>
11
                     this.service.getInfo()
12
                     .pipe(
13
                        map(resp => getInfoSuccessfulAction({info: resp,}))
14
                      )
15
           )
16
       )
17
    );
18
}



This is a very simple example of an effect. It's defined by the getInfoAction  action, and there is a call to service getInfo. Then, it's fired the action, getInfoSuccessfulAction. At this point, everything is straightforward, but what if you need to get some value from @ngrx/store. Well, the good news is you can do it; let me show you how to.

The idea is to inject a Storage instance into the Effect. Then, you can use it in your effect factory method. 

Then, you constructor looks like this:

TypeScript
 




xxxxxxxxxx
1


 
1
 constructor(private actions: Actions, private service: yourService, private store: Store<GameState>) {}



Now, you can use your storage object to get data from your current state. (You can use a Selector.) I am going to show you my create effect method updated to use the Storage object.

TypeScript
 




xxxxxxxxxx
1
13


 
1
   infoEffect = 
2
    createEffect(() => 
3
        this.actions.pipe(
4
            ofType(getInfoAction),
5
            withLatestFrom(this.store.select(getInfoName)),
6
            mergeMap((infoName) =>
7
                     this.service.getInfo(infoName)
8
                     .pipe(
9
                        map(resp => getInfoSuccessfulAction({info: resp,}))
10
                      )
11
           )
12
       )
13
    );



  1. withLatestFrom : The method to use your selector.
  2.  getInfoName : The regular ngrx selector.
  3.  infoName : The value return by the selector (you can use it as a parameter on your call service).

In this way, you can use a value saved into your storage inside your effect. Now, I want to show you an example with more complexity. How you can use this approach when the action used by your effect has parameters. Do not worry about the solution. It's really easy.

This is the action definition with a parameter (A string parameter the parameter's name is greeting).

TypeScript
 




xxxxxxxxxx
1


 
1
export const greetingAction =
2
      createAction('Greeting Action', props<{                                                                     greeting:String,
3
                                       }>());



This is the effect definition using the greetingAction and a value (current user name) from Storage.

TypeScript
 




x
13


 
1
   GreetingEffect = 
2
    createEffect(() => 
3
        this.actions.pipe(
4
            ofType(greetingAction),
5
            withLatestFrom(this.store.select(getUserName)),
6
            mergeMap(([greetingText,userName]) =>
7
                     this.service.sayHello(greetingText,userName)
8
                     .pipe(
9
                        map(resp => greetingActionSuccessfulAction({greeting: resp,}))
10
                      )
11
           )
12
       )
13
    );




Further Reading

  • Angular Tutorial: State Management With NgRx.
TypeScript IT AngularJS Object (computer science) Factory (object-oriented programming) Data (computing) Strings Data Types

Opinions expressed by DZone contributors are their own.

Related

  • JSON-Based Serialized LOB Pattern
  • Rust’s Ownership and Borrowing Enforce Memory Safety
  • Mule 4 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • High-Performance Java Serialization to Different Formats

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook