[Angular] Creating an Observable Store with Rx
Angular with an Store creating Observable RX
2023-09-14 09:00:51 时间
The API for the store is really simple:
/* set(name: string, state: any); select<T>(name: string): Observable<T> */
There are two methods, set() & select().
Store:
import {Observable} from 'rxjs/Observable'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {IState} from './state'; import 'rxjs/add/operator/pluck'; import 'rxjs/add/operator/distinctUntilChanged'; const state: IState = { playList: undefined }; export class Store { /*Because store usually has a default value, BehaviorSubject is suitable for that*/ private subject = new BehaviorSubject<IState>(state); /*Create a observable store*/ private store = this.subject .asObservable() // convert to an observable .distinctUntilChanged(); // performance improve /*Get value from subject*/ get value() { return this.subject.value; } set(name: string, state: any) { const nextState = { ...this.value, [name]: state }; this.subject.next(nextState); } select<T>(name: string): Observable<T> { // get prop value from observable return this.store.pluck(name); } }
interface:
export interface IState { playList: any[] }
Component:
import { Component } from '@angular/core'; import {Store} from './store'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { todos$ = this.store.select<any[]>('todos'); constructor(private store: Store) { this.store.set('todos', [ {id: 1, name: 'Learning Angular'}, {id: 2, name: 'Learning Redux'} ]); } }
<div> <ul *ngFor="let todo of todos$ | async"> <li>{{todo.name}}</li> </ul> </div>
相关文章
- 怎么组织 Angular 项目 |Top 5 技巧
- angular组件的基本使用
- 从 Angular Route 中提前获取数据
- 关于 SAP Spartacus Angular HTTP Interceptor 的拦截顺序
- Angular 面试题汇总2-Component/Service (Angular v8+)
- angular面试题及答案_angular面试
- Angular 14 新的 inject 函数介绍
- 关于 Angular Universal 应用执行时需要 Browser API 的问题
- Angular 应用开发里使用 ForRoot 解决 Lazy Loaded Module 里单例行为丢失的问题
- Angular Feature Modules
- Angular 项目中 angular.json builder 字段的可选项介绍
- Angular 应用里 server.ts 文件的 APP_BASE_HREF token 的用法?
- Oracle中利用WITH子句的使用(oracle中的with)
- Angular用来控制元素的展示与否的原生指令介绍