ngx-model 开源项目教程
项目介绍
ngx-model
是一个用于 Angular 的简单状态管理库,提供了最小化的 API、单向数据流、多模型支持和作为 RxJS Observable 的不可变数据。这个库旨在帮助开发者更轻松地管理应用状态,同时保持代码的简洁和可维护性。
项目快速启动
安装
首先,通过 npm 安装 ngx-model
:
npm install --save ngx-model
导入模块
在你的 Angular 应用模块中导入 NgxModelModule
:
import { NgxModelModule } from 'ngx-model';
@NgModule({
imports: [
NgxModelModule
]
})
export class AppModule { }
创建服务
创建一个服务来管理你的模型数据:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ModelFactory, Model } from 'ngx-model';
@Injectable({
providedIn: 'root'
})
export class TodosService {
private model: Model<Todo[]>;
todos$: Observable<Todo[]>;
constructor(private modelFactory: ModelFactory<Todo[]>) {
this.model = this.modelFactory.create([]); // 创建模型并传递初始数据
this.todos$ = this.model.data$; // 将模型数据作为命名公共属性暴露
}
toggleTodo(id: string) {
const todos = this.model.get(); // 获取原始模型数据
todos.forEach(t => {
if (t.id === id) {
t.done = !t.done;
}
});
this.model.set(todos); // 设置新的模型数据(在突变之后)
}
}
应用案例和最佳实践
案例:待办事项列表
使用 ngx-model
管理一个简单的待办事项列表。
- 定义模型:
interface Todo {
id: string;
title: string;
done: boolean;
}
- 服务实现:
@Injectable({
providedIn: 'root'
})
export class TodosService {
private model: Model<Todo[]>;
todos$: Observable<Todo[]>;
constructor(private modelFactory: ModelFactory<Todo[]>) {
this.model = this.modelFactory.create([]);
this.todos$ = this.model.data$;
}
addTodo(title: string) {
const todos = this.model.get();
todos.push({ id: uuid(), title, done: false });
this.model.set(todos);
}
toggleTodo(id: string) {
const todos = this.model.get();
todos.forEach(t => {
if (t.id === id) {
t.done = !t.done;
}
});
this.model.set(todos);
}
}
- 组件使用:
@Component({
selector: 'app-todos',
template: `
<ul>
<li *ngFor="let todo of todos$ | async">
<input type="checkbox" [checked]="todo.done" (change)="toggleTodo(todo.id)">
{{ todo.title }}
</li>
</ul>
<input #newTodo>
<button (click)="addTodo(newTodo.value)">Add Todo</button>
`
})
export class TodosComponent {
todos$: Observable<Todo[]>;
constructor(private todosService: TodosService) {
this.todos$ = this.todosService.todos$;
}
addTodo(title: string) {
this.todosService.addTodo(title);
}
toggleTodo(id: string) {
this.todosService.toggleTodo(id);
}
}
典型生态项目
ngx-model
可以与其他 Angular 生态系统项目结合使用,例如:
- **Angular Material