ngx-subscribe
Version:
Subscribe decorator to be used in Angular 2+ components, it will automatically subscribe and cleanup observables to component properties.
86 lines • 2.88 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
function setValue(shadow, prop, value) {
if (!shadow.__value)
shadow.__value = {};
if (shadow.__value[prop] !== value) {
shadow.__value[prop] = value;
if (shadow.changeDetector)
shadow.changeDetector.markForCheck();
}
}
function isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
function getValue(shadow, prop, defaultValue) {
if (!shadow.__value) {
return isFunction(defaultValue) ? defaultValue() : defaultValue;
}
return shadow.__value[prop];
}
function subscribe(shadow, prop, obs) {
if (!shadow.__subs)
shadow.__subs = {};
shadow.__subs[prop] = obs.subscribe(function (value) { return setValue(shadow, prop, value); });
}
function unsubscribe(shadow, prop) {
if (!shadow.__subs)
return;
var sub = shadow.__subs[prop];
if (sub) {
sub.unsubscribe();
delete shadow.__subs[prop];
}
}
function unsubscribeAll() {
var self = this;
if (!self.__subs)
return;
for (var _i = 0, _a = Object.getOwnPropertyNames(self.__subs); _i < _a.length; _i++) {
var prop = _a[_i];
self.__subs[prop].unsubscribe();
}
}
function onDestroy() {
var self = this;
if (self.__ngOnDestroy)
self.__ngOnDestroy();
self.__unsubscribeAll();
}
function likeObservable(maybeObservable) {
return !!maybeObservable && typeof (maybeObservable.subscribe) === 'function';
}
/**
* Will define property which will subscribe to the given Observable on set and will return last emited value on get.
*
* @param defaultValue Default value which will be used till observable will emit its value for the first time.
*/
function Subscribe(defaultValue) {
return function (target, propertyKey) {
var proto = target.constructor.prototype;
if (!proto['__unsubscribeAll']) {
var ngOnDestroy = proto['ngOnDestroy'];
if (ngOnDestroy)
proto['__ngOnDestroy'] = ngOnDestroy;
proto['__unsubscribeAll'] = unsubscribeAll;
proto['ngOnDestroy'] = onDestroy;
}
var desc = {
get: function () { return getValue(this, propertyKey, defaultValue); },
set: function (value) {
var self = this;
unsubscribe(self, propertyKey);
// looks like Observable?
if (likeObservable(value)) {
subscribe(self, propertyKey, value);
}
else {
setValue(self, propertyKey, value);
}
}
};
return desc;
};
}
exports.Subscribe = Subscribe;
//# sourceMappingURL=subscribe.js.map
;