Piotr Sikora - Logo - Automatyzacja procesów | AI | JavaScript | Front End | Team Leader
  • Home
  • Services
    • Process Automation
    • AI for Lawyers
  • Blog
  • Quotes
  • Contact
PL/EN

Angular Side Effects with @Effect & NgRx CRUD

  • Home
  • Blog
  • Angular Side Effects with @Effect & NgRx CRUD
Angular Side Effects with @Effect & NgRx CRUD

By Piotr Sikora

  • angular

  • 6 min read

Table of Contents

  • Actions
  • Service
  • @Effect() based CRUD code snippets
  • @Effect() - Get list (posts)
  • @Effect() - Create (post)
  • @Effect() - Update (post)
  • @Effect() - Delete (post)

Angular is giving great tools to build application and NgRx gives you opportunity to manage you app with state. In this article I'm sharing few code snippets which will help you to bring @Effects to work with CRUD application.

Actions

In post.actions.ts file we are creating actions like

import {Action} from '@ngrx/store';

export enum PostActionTypes {
  FetchPosts = '[POST] Fetch Posts',
  FetchPostsError = '[POST] Fetch Posts Error',
  SetPosts = '[POST] Set Posts',

  CreatePost = '[POST] Create Post',
  CreatePostError = '[POST] Create Post Error',
  CreatePostSuccess = '[POST] Create Post Success',

  UpdatePost = '[POST] Update Post',
  UpdatePostError = '[POST] Update Post Error',
  UpdatePostSuccess = '[POST] Update Post Success',

  RemovePost = '[POST] Remove Post',
  RemovePostError = '[POST] Remove Post Error',
  RemovePostSuccess = '[POST] Remove Post Success',

  FetchCurrentPost = '[POST] Fetch Current Post',
  SetCurrentPost = '[POST] Set Current Post',
}

export class FetchPosts implements Action {
  readonly type = PostActionTypes.FetchPosts;

  constructor() {
  }
}

export class FetchPostsError implements Action {
  readonly type = PostActionTypes.FetchPostsError;

  constructor(public payload) {
  }
}

export class SetPosts implements Action {
  readonly type = PostActionTypes.SetPosts;

  constructor(public payload) {
  }
}

export class CreatePost implements Action {
  readonly type = PostActionTypes.CreatePost;

  constructor(public payload) {
  }
}

export class CreatePostError implements Action {
  readonly type = PostActionTypes.CreatePostError;

  constructor(public payload) {
  }
}

export class CreatePostSuccess implements Action {
  readonly type = PostActionTypes.CreatePostSuccess;

  constructor(public payload) {
  }
}

export class RemovePost implements Action {
  readonly type = PostActionTypes.RemovePost;

  constructor(public payload) {
  }
}

export class RemovePostError implements Action {
  readonly type = PostActionTypes.RemovePostError;

  constructor(public payload) {
  }
}

export class RemovePostSuccess implements Action {
  readonly type = PostActionTypes.RemovePostSuccess;

  constructor(public payload) {
  }
}

export class UpdatePost implements Action {
  readonly type = PostActionTypes.UpdatePost;

  constructor(public payload) {
  }
}

export class UpdatePostError implements Action {
  readonly type = PostActionTypes.UpdatePostError;

  constructor(public payload) {
  }
}

export class UpdatePostSuccess implements Action {
  readonly type = PostActionTypes.UpdatePostSuccess;

  constructor(public payload) {
  }
}

export class FetchCurrentPost implements Action {
  readonly type = PostActionTypes.FetchCurrentPost;

  constructor() {
  }
}

export class SetCurrentPost implements Action {
  readonly type = PostActionTypes.SetCurrentPost;

  constructor(public payload) {
  }
}

export type PostAction =
  FetchPosts |
  FetchPostsError |
  SetPosts |
  CreatePost |
  CreatePostError |
  CreatePostSuccess |
  RemovePost |
  RemovePostError |
  RemovePostSuccess |
  UpdatePost |
  UpdatePostError |
  UpdatePostSuccess |
  FetchCurrentPost |
  SetCurrentPost;

So easily said every action has it's invoker like 'UpdatePost' than if action fails the 'UpdatePostError' should be invoked and if Update will succeed 'UpdatePostSuccess' should be invoked.

Service

Post service in post.service.ts file.


@Injectable({
  providedIn: 'root'
})
export class PostService {
  constructor(
    private serverService: ServerService,
    private store: Store<AppState>
  ) {}

  getPosts = () => this.serverService.get(POSTS_URL);
  addPost = (post) => this.serverService.post(POSTS_URL, post);
  removePost = (post) => this.serverService.delete(POSTS_URL + post._id);
  updatePost = (post) => this.serverService.put(POSTS_URL + post._id, post);
}

As you can see there are four methods getPosts, addPost, removePost, updatePost. ServerService is based on standard GET/POST/DELETE/PUT HTTP methods.

In this case POSTS_URL is const string with URL to endpoint like 'http://api.domain.com/posts'.

@Effect() based CRUD code snippets

@Effect() - Get list (posts)

How to use @Effect for Get action

@Effect()
  loadPosts$: Observable<Action> = this.actions$.pipe(
    ofType(PostActionTypes.FetchPosts),
    switchMap(() => {
      return this.postService.getPosts()
        .pipe(
          switchMap((response: Response) => [
            new SetPosts(response.data),
            new StopLoading({error: null, msg: 'Posts loaded'})
          ]),
          catchError(err => of(new FetchPostsError(err)))
        );
    })
  );

@Effect() - Create (post)

How to use @Effect for Create action

@Effect()
  createPosts$: Observable = this.actions$.pipe(
    ofType(PostActionTypes.CreatePost),
    switchMap((action) =&gt; {
      return this.postService.addPost(action['payload'])
        .pipe(
          switchMap((response: Response) =&gt; [
            new CreatePostSuccess(response.data),
            new StopLoading({error: null, msg: 'Post loaded'})
          ]),
          catchError(err =&gt; of(new CreatePostError(err)))
        );
    })
  );

@Effect() - Update (post)

How to use @Effect for Update action

@Effect()
  updatePost$: Observable = this.actions$.pipe(
    ofType(PostActionTypes.UpdatePost),
    switchMap((action) =&gt; {
      return this.postService.updatePost(action['payload'])
        .pipe(
          switchMap((response: Response) =&gt; [
            new UpdatePostSuccess(response.data),
            new StopLoading({error: null, msg: 'Post updated'})
          ]),
          catchError(err =&gt; of(new UpdatePostError(err)))
        );
    })
  );

@Effect() - Delete (post)

How to use @Effect for Delete action

@Effect()
  removePost$: Observable = this.actions$.pipe(
    ofType(PostActionTypes.RemovePost),
    switchMap((action) =&gt; {
      return this.postService.removePost(action['payload'])
        .pipe(
          switchMap((response: Response) =&gt; [
            new RemovePostSuccess(response.data),
            new StopLoading({error: null, msg: 'Post removed'})
          ]),
          catchError(err =&gt; of(new RemovePostError(err)))
        );
    })
  );

Share this article

TwitterLinkedInFacebook

Tags:

  • #angular

  • #javascript

  • #ngrx

  • #state-machine

  • #state-management

Categories

after-hours(1)AI(7)ai-en(1)angular(4)automatic-tests(1)Automation(2)cryptography(1)css(8)CyberSecurity(2)Development(6)DevOps(1)events(3)javascript(11)n8n(10)ollama(1)security(2)seo(1)

Recent Posts

Testing Kimi Code: First Impressions from Web and CLI

Development

Testing Kimi Code: First Impressions from Web and CLI

Why You Shouldn't Cram Multiple Webhooks Into One n8n Workflow

Automation

Why You Shouldn't Cram Multiple Webhooks Into One n8n Workflow

DRY, WET, AHA: Finding the Right Balance in Code Reuse

Development

DRY, WET, AHA: Finding the Right Balance in Code Reuse

API vs Webhook: Understanding the Difference

Development

API vs Webhook: Understanding the Difference

RTCROS Framework: Structure Your Prompts for Better AI Results

AI

RTCROS Framework: Structure Your Prompts for Better AI Results

About Me

Piotr Sikora - Process Automation | AI | n8n | Python | JavaScript

Piotr Sikora

Process Automation Specialist

I implement automation that saves time and money, streamlines operations, and increases the predictability of results. Specializing in process automation, AI implementation, and workflow optimization using n8n, Python, and JavaScript.

n8n Workflows

n8n workflow automation templates

Explore my workflow templates on n8n. Ready-to-use automations for blog management, data collection, and AI-powered content processing.

3Workflow Templates
View Templates

• Auto-Categorize Blog Posts with AI

• Collect LinkedIn Profiles

• Export WordPress Posts for SEO

Tags

activepiecesafter-hoursahrefsaiAI cost reductionai-agentsai-automationangularantigravityapiAqua Securityarcade-gamesarchitectureautomationbackendbest-practicescadillacs-and-dinosaurschatbotchatgptCI/CD
“Rule number one: never lose money. Rule number two: never forget rule number one.”
Warren Buffett
View more quotes

Similar Articles

Discover more related content

State Management: Prepare Environment Properly

State Management: Prepare Environment Properly

To start project we will need to create node project. I assume that you have installed Node.js on your machine.

DevMeeting Angular 2: Exploring the Future

DevMeeting Angular 2: Exploring the Future

Last weekend Ive been with my friends at DevMeeting about Angular 2.0 in Krakow.

Fix Angular 2 Pipes: Resolve TypeError

Fix Angular 2 Pipes: Resolve TypeError

Ive been trying to build simple filtering in application -> Show-ur-bugs

Piotr Sikora | ai | n8n | javascript | python

Let's get to know each other!

Get in touch with me
Piotr Sikora | Process Automation  | AI Implementation 🤖 | Technology Consulting
Quick links
  • Home
  • Blog
  • Contact
Contact
  • piotr.sikora.ck@gmail.com
  • +48 505 684 661

© Piotr Sikora 2026 | All Rights Reserved