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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • How to Convert XLS to XLSX in Java
  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.2K 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!