1. First step is creating action creator

Action name should be clear which page, which functionality, what is the action name

"[Load Courses Effect] All Courses Loaded",
"[Courses Resolver] Load All Courses"

Action

import { createAction, props } from "@ngrx/store";
import { Course } from "./model/course"; export const loadAllCourse = createAction(
"[Courses Resolver] Load All Courses"
); export const allCoursesLoaded = createAction(
"[Load Courses Effect] All Courses Loaded",
props<{ courses: Course[] }>()
);

action types:

To make actions easy to work with, can create action types: basic it is just a improt and re-export

// actions-types.ts

import * as CoursesAction from "./cuorses.actions";

export { CoursesAction };

Effects:

Using 'createEffect', first param is a function to catch the event stream, second param is the options, can set '{dispatch: false}' which mean no other dispath event for this effect.

import { Injectable } from "@angular/core";
import { Actions, ofType } from "@ngrx/effects";
import { createEffect } from "@ngrx/effects";
import { CoursesAction } from "./actions-types";
import { CoursesHttpService } from "./services/courses-http.service";
import { concatMap, map, tap } from "rxjs/operators"; @Injectable()
export class CoursesEffects {
constructor(
private action$: Actions,
private coursesHttpService: CoursesHttpService
) {} loadAllCourses$ = createEffect(() =>
this.action$.pipe(
ofType(CoursesAction.loadAllCourse),
concatMap(() => this.coursesHttpService.findAllCourses()),
map(courses => CoursesAction.allCoursesLoaded({ courses }))
)
);
}
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { Actions, ofType, createEffect } from "@ngrx/effects";
import { AuthActions } from "./action-types"; import { tap } from "rxjs/operators"; @Injectable()
export class AuthEffects {
constructor(private action$: Actions, private router: Router) {} login$ = createEffect(
() =>
this.action$.pipe(
ofType(AuthActions.login),
tap(action => {
localStorage.setItem("user", JSON.stringify(action.user));
})
),
{ dispatch: false }
); logout$ = createEffect(
() =>
this.action$.pipe(
ofType(AuthActions.logout),
tap(action => localStorage.removeItem("user")),
tap(() => this.router.navigateByUrl("/"))
),
{ dispatch: false }
);
}

Register effect:

@NgModule({
imports: [
...
EffectsModule.forFeature([AuthEffects])
],
...
})

Reducers:

Reducer mainly take care five things:

1. Define state interface

2. Creating adapter

3. Generate intialize state

4. Generate next state for one action

5. Export selector

1. Initial state:

First we need to have the interface defined for the state:

/*
export interface CoursesState {
entities: { [key: number]: Course };
ids: number[];
}*/

NgRx provide API to create state interface:

import { EntityState, createEntityAdapter } from "@ngrx/entity";

export interface CoursesState extends EntityState<Course> {
/**Extend the entity here */
allCoursesLoaded: boolean;
}

'EntityState' contains 'entities' & 'ids'.

And we can extends interface by providing extra props: for example: 'allCoursesLoaded'.

2. Create Adapter:

export const adapter = createEntityAdapter<Course>({
sortComparer: compareCourses
// selectId: course => course.id // NgRx use 'id' by default
});

3. Generate initial state:

We can use 'adapter' to create initialstate

export const initCoursesState = adapter.getInitialState({
allCoursesLoaded: false
});

4. Create Reducer:

export const coursesReducer = createReducer(
initCoursesState,
on(CoursesAction.allCoursesLoaded, (state, action) =>
adapter.addAll
(action.courses, { ...state, allCoursesLoaded: true }) // next state
)
);

5. Export selector:

export const { selectAll } = adapter.getSelectors();

Full code:

import { Course, compareCourses } from "../model/course";
import { EntityState, createEntityAdapter } from "@ngrx/entity";
import { createReducer, on } from "@ngrx/store";
import { CoursesAction } from "../actions-types";
/*
export interface CoursesState {
entities: { [key: number]: Course };
ids: number[];
}*/ export interface CoursesState extends EntityState<Course> {
/**Extend the entity here */
allCoursesLoaded: boolean;
} export const adapter = createEntityAdapter<Course>({
sortComparer: compareCourses
// selectId: course => course.id // NgRx use 'id' by default
}); export const initCoursesState = adapter.getInitialState({
allCoursesLoaded: false
}); export const coursesReducer = createReducer(
initCoursesState,
on(CoursesAction.allCoursesLoaded, (state, action) =>
adapter.addAll(action.courses, { ...state, allCoursesLoaded: true })
)
); export const { selectAll } = adapter.getSelectors();

5. Selector:

Selecotor mainly has two API: createFeatureSelector & createSelector:

import { createSelector, createFeatureSelector } from "@ngrx/store";
import * as fromCourses from "./reducers/courses.reducers"; export const selectCoursesState = createFeatureSelector<
fromCourses.CoursesState
>("courses"
); export const selectAllCourses = createSelector(
selectCoursesState,
fromCourses.selectAll
); export const selectAllCoursesLoaded = createSelector(
selectCoursesState,
state => state.allCoursesLoaded
); export const selectBeginnerCourses = createSelector(
selectAllCourses,
courses => courses.filter(course => course.category === "BEGINNER")
); export const selectAdvancedCourses = createSelector(
selectAllCourses,
courses => courses.filter(course => course.category === "ADVANCED")
); export const selectPromoTotal = createSelector(
selectAllCourses,
courses => courses.filter(course => course.promo).length
);

Component:

import { Component, OnInit } from "@angular/core";
import { compareCourses, Course } from "../model/course";
import { Observable } from "rxjs";
import { defaultDialogConfig } from "../shared/default-dialog-config";
import { EditCourseDialogComponent } from "../edit-course-dialog/edit-course-dialog.component";
import { MatDialog } from "@angular/material";
import { Store, select } from "@ngrx/store";
import { AppState } from "../../reducers";
import * as coursesSelector from "../courses.selectors"; @Component({
selector: "home",
templateUrl: "./home.component.html",
styleUrls: ["./home.component.css"]
})
export class HomeComponent implements OnInit {
promoTotal$: Observable<number>; beginnerCourses$: Observable<Course[]>; advancedCourses$: Observable<Course[]>; constructor(private dialog: MatDialog, private store: Store<AppState>) {} ngOnInit() {
this.reload();
} reload() {
this.beginnerCourses$ = this.store.pipe(
select(coursesSelector.selectBeginnerCourses)
); this.advancedCourses$ = this.store.pipe(
select(coursesSelector.selectAdvancedCourses)
); this.promoTotal$ = this.store.pipe(
select(coursesSelector.selectPromoTotal)
);
} onAddCourse() {
const dialogConfig = defaultDialogConfig(); dialogConfig.data = {
dialogTitle: "Create Course",
mode: "create"
}; this.dialog.open(EditCourseDialogComponent, dialogConfig);
}
}

select:

'select' operator can be used in many places, mainly if you want to get piece of data from store, for example, it can be used in resolver as well:

import { Injectable } from "@angular/core";
import {
Resolve,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from "@angular/router";
import { Observable } from "rxjs";
import { Store, select } from "@ngrx/store";
import { AppState } from "../reducers";
import { CoursesAction } from "./actions-types";
import { tap, first, finalize, filter } from "rxjs/operators";
import { adapter } from "./reducers/courses.reducers";
import { selectAllCoursesLoaded } from "./courses.selectors"; @Injectable()
export class CoursesResolver implements Resolve<any> {
loading = false;
constructor(private store: Store<AppState>) {} resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
return this.store.pipe(
select(selectAllCoursesLoaded),
tap(courseLoaded => {
if (!this.loading && !courseLoaded) {
this.loading = true;
this.store.dispatch(CoursesAction.loadAllCourse());
}
}),
// this resolve need to complete, so we can use first()
filter(courseLoaded => courseLoaded),
first(),
finalize(() => (this.loading = false))
);
}
}

[NgRx 8] Basic of NgRx8的更多相关文章

  1. ngRx 官方示例分析 - 3. reducers

    上一篇:ngRx 官方示例分析 - 2. Action 管理 这里我们讨论 reducer. 如果你注意的话,会看到在不同的 Action 定义文件中,导出的 Action 类型名称都是 Action ...

  2. [转]VS Code 扩展 Angular 6 Snippets - TypeScript, Html, Angular Material, ngRx, RxJS & Flex Layout

    本文转自:https://marketplace.visualstudio.com/items?itemName=Mikael.Angular-BeastCode VSCode Angular Typ ...

  3. Atitit HTTP 认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结

    Atitit HTTP认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结 1.1. 最广泛使用的是基本验证 ( ...

  4. Basic Tutorials of Redis(9) -First Edition RedisHelper

    After learning the basic opreation of Redis,we should take some time to summarize the usage. And I w ...

  5. Basic Tutorials of Redis(8) -Transaction

    Data play an important part in our project,how can we ensure correctness of the data and prevent the ...

  6. Basic Tutorials of Redis(7) -Publish and Subscribe

    This post is mainly about the publishment and subscription in Redis.I think you may subscribe some o ...

  7. Basic Tutorials of Redis(6) - List

    Redis's List is different from C#'s List,but similar with C#'s LinkedList.Sometimes I confuse with t ...

  8. Basic Tutorials of Redis(5) - Sorted Set

    The last post is mainly about the unsorted set,in this post I will show you the sorted set playing a ...

  9. Basic Tutorials of Redis(4) -Set

    This post will introduce you to some usages of Set in Redis.The Set is a unordered set,it means that ...

随机推荐

  1. CEF4Delphi 常用设置

    CEF4Delphi是由 SalvadorDíazFau 创建的一个开源项目,用于在基于Delphi的应用程序中嵌入基于Chromium的浏览器. CEF4Delphi 基于Henri Gourves ...

  2. Python安装-Pycharm+Anaconda

    1.初识Python Python是一门非常简单优雅的编程语言,可以用极少的代码就能实现强大的功能,而且学习起来十分简单,没有编程基础也可轻松入门.其功能强大,特别是第三方库的库的支持,使得开发方便十 ...

  3. Oracle数据库连接超时

    关于Oracle数据库的连接失败问题,有N种情况都会导致,这次遇到的是一般开发或者运维人员难以发现的 场景: 有一台机A能够正常连接数据库并正常运行,机器B连接失败 32位WebService程序基于 ...

  4. 逆波兰表达式求值 java实现代码

    根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰表达式. 说明: 整数除法只保留整数部分. 给定逆波兰表达式总是有效的.换句话说 ...

  5. 论PM与团队与敏捷开发

    敏捷开发是每个有追求的PM都会去读的书 敏捷开发是很少程序会去读的书 敏捷开发是团体其他人很少会读的书 然而, 据我的 所见, 所闻, 所论 敏捷开发在大家的脑袋里分为很多种版本 既有可以一辩的新鲜思 ...

  6. vue-cli搭建的项目打包之后报“资源路径错误&资源文件找不到“

    此方式vue脚手架是3.0版本,2.0版本见最下面//在项目的根目录下(和package.json文件同级)新建一个文件vue.config.js的文件,将此段代码复制进去.module.export ...

  7. Referenced file contains errors (xml文件第一行小红叉错误)

    转自:http://www.manongjc.com/article/30401.html 在eclipse中开发网页时,经常会遇到写xml文件时第一行无缘无故报错.在最左面的行数上面报出一个小红叉, ...

  8. UCOSIII系统内部任务

    1. 空闲任务 空闲任务是UCOSIII创建的第一个任务 空闲任务是UCOSIII必须创建的 空闲任务优先级总是为OS_CFG_PRIO_MAK-1 空闲任务中不能调用任何可使空闲任务进入等待态的函数 ...

  9. 那些年伴我一起成长的SAP装备

    今天这篇文章无关技术,我们来聊聊SAP装备,即打上了SAP logo的那些物品. 但凡在SAP圈子工作过一段时间的从业者们,手上或多或少都拥有一些此类装备.Jerry当然也不例外,这些装备无论物品本身 ...

  10. SpringBoot+SpringCloud+vue+Element开发项目——搭建开发环境

    1.新建一个项目