UNPKG

ngx-stateful

Version:

Be obnoxiously clear about which of your Angular components own state

50 lines (49 loc) 1.91 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.StatefulComponent = void 0; var rxjs_1 = require("rxjs"); var operators_1 = require("rxjs/operators"); var StatefulComponent = /** @class */ (function () { function StatefulComponent(_state) { this._state = new rxjs_1.BehaviorSubject(null); this.state$ = this._state.asObservable(); this.setState(_state); } Object.defineProperty(StatefulComponent.prototype, "state", { get: function () { return this._state.value; }, enumerable: false, configurable: true }); StatefulComponent.prototype.select = function (selector) { return this.state$.pipe(operators_1.map(selector), operators_1.distinctUntilChanged()); }; StatefulComponent.prototype.selectKey = function (key) { return this.select(function (state) { return state[key]; }); }; StatefulComponent.prototype.onChange = function (selector) { return this.select(selector).pipe(operators_1.pairwise()); }; StatefulComponent.prototype.onKeyChange = function (key) { return this.onChange(function (state) { return state[key]; }); }; StatefulComponent.prototype.setState = function (state) { this._state.next(typeof state === 'function' ? state(this._state.value) : (__assign(__assign({}, this._state.value), state))); }; return StatefulComponent; }()); exports.StatefulComponent = StatefulComponent;