[Angular2] @Ngrx/store and @Ngrx/effects learning note

Just sharing the learning experience related to @ngrx/store and @ngrx/effects.

 

In my personal opinion, I fell there are tow different types of coding style by using 

  1. @ngrx/store only

  2. @ngrx/store + @ngrx/effects

 

So How we do with only ngrx/store?

Controller: 

复制代码
 deleteItem(item: Item) {
    this.subs['deleteItem'] = this.itemsService.deleteItem(item)
      .subscribe(
        (res) => {
          console.log("Delete Item success", JSON.stringify(res, null, 2))
          this.resetItem();
        },
        (err) => alert("error")
      );
  }
复制代码

Service:

export class ItemsService {
  items$: Observable<Item[]> = this.store.select('items');

  constructor(
    private http: Http,
    private store: Store<AppStore>,
    private actions: ItemsActions
  ) {}
  deleteItem(item: Item) {
    return this.http.delete(`${BASE_URL}${item.id}`)
      .do(action => this.store.dispatch({ type: DELETE_ITEM, payload: item }));
  }

Reducer:

    case DELETE_ITEM:
      return state.filter(item => {
        return item[comparator] !== action.payload[comparator];
      });

As you can see, the working flow is like that:

  1. Form controller we call the Service to delete the item
  2. Service do the http call to remove the item
  3. Then we have '.do()' method to create side effect, call dispatch 
  4. Since the return from Service is Observable, we subscribe form the controller.
  5. Inside successfully handler, we can do any other ui side effect.

 

ngrx/store + ngrx/effects:

Controller: 

  deleteWidget(widget: Widget) {
    this.store.dispatch({type: DELETE_WIDGET, payload: widget});
  }

Service:

  deleteWidget(widget: Widget) {
    return this.http.delete(`${BASE_URL}${widget.id}`);
  }

Effect:

  @Effect() delete$: Observable<Action> = this.actions$
    .ofType(DELETE_WIDGET)
    .map(action => action.payload)
    .switchMap((widget)=>{
      return this.widgetsService.deleteWidget(widget)
                .map(success => console.log("success"))
                .catch(() => of("error")) // catch expect to get an observable back
    });

Reducer:

    case DELETE_WIDGET:
      return state.filter(widget => {
        return widget[comparator] !== action.payload[comparator];
      });

 

So the work flow for ngrx/store + ngrx/effects:

  1. From the controller, we just dispatch the action.
  2. Effect listening the actions that dispatched, and trigger 'ofType' the same is dispatched action from controller.
  3. Inside effect, we call service to delete the widget.
  4. If http request is success, we actually can dispatch another UI action that will do the UI rendering.
  5. If http reuqest is faild, we catch it and you actually can dispatch another UI action that will show the error in UI.

Github

 

Summary:

By using only ngrx/store, we are still using the coding style we get used to, like controller talking to the service, after service done its job, return back to controller, let controller do whatever necessary.

 

By using ngrx/store + ngrx/effects, we are actullay walking into RxJS + Redux world, everything goes reactive, everything should have a reducer even it is UI rendering stuff.

 

I am not sure which way is better. My point is I am using Redux partten, take advantage of RxJS to help me handle state management esailer. But I don't know to overkill, everything conver to Observable and reducers style is way to far from the starting point -- state management.

posted @   Zhentiw  阅读(386)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-11-11 [Javascript] Intro to the Web Audio API
2014-11-11 [Firebase] 4. Firebase Object related Database
2014-11-11 [Firebase] 3. Firebase Simple Login Form
点击右上角即可分享
微信分享提示