Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Created March 29, 2018 18:54
Show Gist options
  • Select an option

  • Save beardedtim/df26d3545f33b489381f2b57e96405e9 to your computer and use it in GitHub Desktop.

Select an option

Save beardedtim/df26d3545f33b489381f2b57e96405e9 to your computer and use it in GitHub Desktop.
AngularJS Redux Example
import { Component, Inject, Input } from 'core/decorators';
import { actions, Notification } from 'core/store/ducks/notifications';
import { ReduxProvider } from 'core/store/utilities/provider';
import './notification.item.scss';
@Component({
selector: 'notificationItem',
template: require('./notification.item.html')
})
export class NotificationItemComponent {
@Input('<')
public notification: Notification;
private unsubscribe: () => void;
constructor(
@Inject('$redux') private $redux: ReduxProvider
) {}
$onInit() {
this.unsubscribe = this.$redux.connect(
state => ({
notificaton: state.activeNotification,
}),
dispatch => ({
togglePin: (payload) => dispatch(actions.togglePin(payload)),
})
)(this);
}
}
import * as angular from 'angular';
import createStore from 'core/store';
export class ReduxProvider {
public $get;
private store: any;
constructor() {
this.connect = this.connect.bind(this);
this.$get = [() => {
this.store = createStore();
return Object.assign({}, this.store, {
connect: this.connect
});
}];
}
connect(
mapStateToThis = (...args) => ({}),
mapDispatchToThis = (...args) => ({})
) {
return instance => {
const { getState, dispatch } = this.store;
const state = getState();
const props = mapStateToThis(state);
const actions = mapDispatchToThis(dispatch);
Object.assign(instance, props, actions);
return this.store.subscribe(() => {
const nextState = getState();
const p = mapStateToThis(nextState);
const a = mapDispatchToThis(dispatch);
return Object.assign(instance, p, a);
});
};
}
}
export default angular.module('redux', [])
.provider('$redux', ReduxProvider)
.name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment