I am new to Rxjs I am trying understand BehaviourSubject below is my code
export interface State {
items: Items[]
}
const defaultState = {
items: []
};
const _store = new BehaviorSubject<State>(defaultState);
@Injectable()
export class Store {
private _store = _store;
changes = this._store.distinctUntilChanged()
.do(() => console.log('changes'));
setState(state: State) {
this._store.next(state);
}
getState() : State {
return this._store.value;
}
purge() {
this._store.next(defaultState);
}
}
When i run my project then i get this error in my console
platform-browser.umd.js:1900 EXCEPTION: Error: Uncaught (in promise):
EXCEPTION: Error during instantiation of Store! (StoreHelper -> Store).
ORIGINAL EXCEPTION: TypeError: this._store.distinctUntilChanged is not a function
Can anyone help me out. Also if I am trying to do is to create a Store for my model objects so if there is any other simpler way feel free to suggest it.
Any help is appreciated.
1. First create a BehaviorSubject in order service which holds the initial state of order count ,so that it can be used by any component. 2. Now all observers(3 components) need to subscribe to source observable to get current value and show it on UI.
you have to import entire rxJs library or the specific one for this.
import 'rxjs/add/operator/distinctUntilChanged';
Update rxjs > 5.5 with Pipeable Operators,
import { distinctUntilChanged } from 'rxjs/operators';
Pipeable operators helps building and tree shaking.
To learn more on the benefits of Pipeable operators you may look in here.
Hope this helps!!
You actually have to import all operators (that's do
and distinctUntilChanged
) and the BehaviorSubject
as well.
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
See plnkr demo: http://plnkr.co/edit/Wbqv95EiG8BnzC8BpD7E?p=preview
Btw, I'd be careful with statements such as private _store = _store
because it makes it very hard to read even though it does what you want.
This is generated from https://www.typescriptlang.org/play/.
define(["require", "exports"], function (require, exports) {
"use strict";
var _store = new BehaviorSubject(defaultState);
var Store = (function () {
function Store() {
this._store = _store;
this.changes = this._store.distinctUntilChanged()
.do(function () { return console.log('changes'); });
}
Store.prototype.setState = function (state) {
console.log(_store);
this._store.next(state);
};
Store.prototype.getState = function () {
return this._store.value;
};
Store.prototype.purge = function () {
this._store.next(defaultState);
};
return Store;
}());
exports.Store = Store;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With