本文摘自PHP中文网,作者青灯夜游,侵删。
Angular中什么是NgRx/Store框架?有什么用?本篇文章就来带大家了解一下NgRx/Store数据状态管理框架,ngrx/store中的基本原则,通过示例了解一下该框架的简单用法。【相关教程推荐:《angular教程》】
ngrx/store
是基于RxJS
的状态管理库,其灵感来源于Redux
。在NgRx
中,状态是由一个包含action
和reducer
的函数的映射组成的。Reducer
函数经由action
的分发以及当前或初始的状态而被调用,最后由reducer
返回一个不可变的状态。
状态管理
在前端大型复杂Angular/AngularJS
项目的状态管理一直是个让人头疼的问题。在AngularJS(1.x版本)中,状态管理通常由服务,事件,$rootScope
混合处理。在Angular中(2+版本),组件通信让状态管理变得清晰一些,但还是有点复杂,根据数据流向不同会用到很多方法。
ngrx/store中的基本原则
视图层通过dispatch
发起一个行为(action)、Reducer
接收action
,根据action.type
类型来判断执行、改变状态、返回一个新的状态给store
、由store
更新state
。
State
(状态) 是状态(state
)存储器Action
(行为) 描述状态的变化Reducer
(归约器/归约函数) 根据先前状态以及当前行为来计算出新的状态,里面的方法为纯函数- 状态用
State
的可观察对象,Action
的观察者――Store
来访问
Actions(行为)
Actions
是信息的载体,它发送数据到reducer
,然后reducer
更新store
。Actions
是store
能接受数据的唯一方式。
在ngrx/store
里,Action
的接口是这样的:
1 2 3 4 5 |
|
type
描述期待的状态变化类型。比如,添加待办 ADD_TODO
,增加 DECREMENT
等。payload
是发送到待更新store
中的数据。store
派发action
的代码类似如下:
1 2 3 4 5 |
|
Reducers(归约器)
Reducers
规定了行为对应的具体状态变化。是纯函数,通过接收前一个状态和派发行为返回新对象作为下一个状态的方式来改变状态,新对象通常用Object.assign
和扩展语法来实现。
1 2 3 4 5 6 7 8 9 |
|
开发时特别要注意函数的纯性。因为纯函数:
- 不会改变它作用域外的状态
- 输出只决定于输入
- 相同输入,总是得到相同输出
Store(存储)
store
中储存了应用中所有的不可变状态。ngrx/store
中的store
是RxJS
状态的可观察对象,以及行为的观察者。
可以利用Store
来派发行为。也可以用Store的select()
方法获取可观察对象,然后订阅观察,在状态变化之后做出反应。
上面我们描述的是基本流程。在实际开发过程中,会涉及API请求、浏览器存储等异步操作,就需要effects
和services
,effects
由action
触发,进行一些列逻辑后发出一个或者多个需要添加到队列的action
,再由reducers
处理。
使用ngrx/store框架开发应用,始终只维护一个状态,并减少对API的调用。
简单示例
简单介绍一个管理系统的登录模块。
创建Form表单
1、增加组件:LoginComponent
,主要就是布局,代码为组件逻辑
2、定义用户:User Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
3、添加表单:在组件LoginComponent
增加Form
表单
NGRX Store
按照上述的4个原则定义相应的Actions
reducers
定义状态在文件
auth.reducers.ts
中创建状态,并初始化1
2
3
4
5
6
7
8
9
10
11
export interface AuthState {
isAuthenticated: boolean;
user: User |
null
;
errorMessage: string |
null
;
}
export const initialAuthState: AuthState = {
isAuthenticated:
false
,
user:
null
,
errorMessage:
null
};
actions
定义行为1
2
3
4
5
6
7
8
9
10
export enum AuthActionTypes {
Login =
"[Auth] Login"
,
LoginSuccess =
"[Auth] Login Success"
,
LoginFailure =
"[Auth] Login Failure"
}
export class Login implements Action {
readonly type = AuthActionTypes.Login;
constructor(public payload: any) {}
}
service
实现数据交互(服务器)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Injectable()
export class AuthService {
private BASE_URL =
"api/user"
;
constructor(private http: HttpClient) {}
getToken(): string {
return
localStorage.getItem(
"token"
);
}
login(email: string, pwd: string): Observable<any> {
const url = `${
this
.BASE_URL}/login`;
return
this
.http.post<User>(url, { email, pwd });
}
}
effects侦听从Store调度的动作,执行某些逻辑,然后分派新动作
一般情况下只在这里调用API
通过返回一个action给reducer进行操作来改变store的状态
effects总是返回一个或多个action(除非
@Effect with {dispatch: false})
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Effect()
Login: Observable<any> =
this
.actions.pipe(
ofType(AuthActionTypes.Login),
//执行Login响应
map((action: Login) => action.payload),
switchMap(payload => {
return
this
.authService.login(payload.email, payload.password).pipe(
map(user => {
return
new
LoginSuccess({ uid: user.id, email: payload.email });
}),
catchError(error => {
return
of(
new
LoginFailure(error));
})
);
})
);
//失败的效果
@Effect({ dispatch:
false
})
LoginFailure: Observable<any> =
this
.actions.pipe(ofType(AuthActionTypes.LoginFailure));
//成功的效果
@Effect({ dispatch:
false
})
LoginSuccess: Observable<any> =
this
.actions.pipe(
ofType(AuthActionTypes.LoginSuccess),
tap(user => {
localStorage.setItem(
"uid"
, user.payload.id);
this
.router.navigateByUrl(
"/sample"
);
})
);
完
更多编程相关知识,请访问:编程视频!!
以上就是一文快速了解Angular中的NgRx/Store框架的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
了解一下Angular中的@input()和@output()
深入了解Angular中的hostbinding和hostlistener装饰器
更多相关阅读请进入《Angular》频道 >>
Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者