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
Newsletter
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

  • Full-Text Search Meets the Graph: Apache Lucene Inside Neo4j
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard
  • AI-Powered CI Test Failure Triage
  • Genkit Flows on Kubernetes, Routed by a Decision Model: senro + jev in Go

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Apr. 24, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
19.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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