new model using redux store - version 1

parent 6418ebaf
......@@ -8,14 +8,17 @@
},
"scripts": {
"start": "webpack-dashboard -- webpack --progress --colors --watch --display-error-details --display-cached",
"build": "webpack --progress --colors --watch --display-error-details --display-cached"
"build": "webpack --progress --colors --watch --display-error-details --display-cached",
"typings": "rimraf typings/ && typings install"
},
"devDependencies": {
"@types/node": "^6.0.48",
"angular2-router-loader": "^0.3.4",
"babel-core": "^6.20.0",
"babel-loader": "^6.2.9",
"babel-preset-env": "^1.1.4",
"babel-preset-es2015": "^6.18.0",
"babel-preset-stage-1": "^6.16.0",
"node-sass": "^4.0.0",
"sass-loader": "^4.0.2",
"to-string-loader": "^1.1.5",
......@@ -43,8 +46,10 @@
"file-loader": "^0.9.0",
"html-webpack-plugin": "^2.24.1",
"immutable": "^3.8.1",
"ng2-redux": "^5.1.0",
"ng2-smart-table": "^0.4.0-5",
"raw-loader": "^0.5.1",
"redux": "^3.6.0",
"reflect-metadata": "0.1.8",
"rimraf": "^2.4.3",
"rxjs": "^5.0.0-rc.3",
......
import { COURSEFIELDS_RECEIVED, COURSEFIELDS_SELECTED } from '../constants';
import { Injectable } from '@angular/core';
import { NgRedux } from 'ng2-redux';
import { IAppState } from '../store';
import { HelperDataService } from '../services/helper-data-service';
@Injectable()
export class CourseFieldsActions {
constructor(
private _ngRedux: NgRedux<IAppState>,
private _hds: HelperDataService) {}
getCourseFields = ({ }) => {
return this._hds.getCourseFields().then(courseFields => {
return this._ngRedux.dispatch({
type: COURSEFIELDS_RECEIVED,
payload: {
courseFields
}
});
});
};
}
import { CourseFieldsActions } from './coursefields.actions';
const ACTION_PROVIDERS = [ CourseFieldsActions ];
export {
CourseFieldsActions,
ACTION_PROVIDERS,
};
......@@ -2,5 +2,6 @@ export class AppSettings {
public static get API_ENDPOINT(): string {
// return 'http://localhost/dist';
return 'http://eepal.dev/drupal';
// return 'http://eduslim2.minedu.gov.gr/drupal';
}
}
import 'reflect-metadata';
import 'babel-polyfill';
import 'core-js/es6';
import 'core-js/es7/reflect';
import { NgModule } from '@angular/core';
import { NgReduxModule, DevToolsExtension, NgRedux } from 'ng2-redux';
import {BrowserModule} from '@angular/platform-browser';
import {
FormsModule,
......@@ -20,11 +24,11 @@ import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import Main from './containers/main';
import { APP_ROUTER_PROVIDERS, APP_DECLARATIONS } from './app.routes';
// import { TodoService, FormatService } from './components/todo-app/todo-service';
/* Here we import services */
// import Service1 from './services/service1';
import {HelperDataService} from './services/helper-data-service';
import { ACTION_PROVIDERS } from './actions';
import Home from './components/home';
import { Ng2SmartTableModule } from 'ng2-smart-table';
class MyLocalization extends NgLocalization {
......@@ -43,7 +47,8 @@ class MyLocalization extends NgLocalization {
ReactiveFormsModule,
APP_ROUTER_PROVIDERS,
HttpModule,
Ng2SmartTableModule
Ng2SmartTableModule,
NgReduxModule
],
declarations: [
Main,
......@@ -54,7 +59,10 @@ class MyLocalization extends NgLocalization {
{ provide: APP_BASE_HREF, useValue: '/' },
{ provide: LocationStrategy, useClass: HashLocationStrategy },
{ provide: NgLocalization, useClass: MyLocalization },
DevToolsExtension,
ACTION_PROVIDERS,
// Service1, again services here
HelperDataService,
]
})
class AppModule {}
......
......@@ -2,6 +2,10 @@ import {Component, OnInit} from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import {Injectable} from "@angular/core";
import {CourseFieldsActions} from '../../actions/coursefields.actions';
import { DevToolsExtension, NgRedux, select } from 'ng2-redux';
import { ICourseField, ICourseFields } from '../../store/coursefields/coursefields.types';
import { IAppState } from '../../store/store';
import {
FormBuilder,
......@@ -9,7 +13,6 @@ import {
FormControl,
FormArray
} from '@angular/forms';
import { CourseField } from './coursefield';
import {AppSettings} from '../../app.settings';
@Component({
......@@ -17,14 +20,14 @@ import {AppSettings} from '../../app.settings';
template: `
<form [formGroup]="formGroup">
<div formArrayName="formArray">
<div *ngIf="courseFields.length === 0" class="loading">Loading&#8230;</div>
<div *ngFor="let control of cfs.controls; let i=index">
<div *ngIf="courseFields$.length === 0" class="loading">Loading&#8230;</div>
<div *ngFor="let courseField$ of courseFields$ | async; let i=index">
<div class="row">
<div class="col-md-2 pull-right">
<input type="checkbox" formControlName="{{i}}">
</div>
<div class="col-md-10 pull-left">
{{courseFields[i].name}}
{{courseField$.name}}
</div>
</div>
</div>
......@@ -35,65 +38,26 @@ import {AppSettings} from '../../app.settings';
`
})
@Injectable() export default class CourseFieldsSelect implements OnInit {
private courseFields$: Observable<ICourseFields>;
public formGroup: FormGroup;
public cfs = new FormArray([]);
public courseFields: CourseField[];
constructor(private http: Http, private fb: FormBuilder) {
this.courseFields = [];
constructor(private http: Http, private fb: FormBuilder, private _cfa: CourseFieldsActions, private _ngRedux: NgRedux<IAppState>) {
this.formGroup = this.fb.group({
formArray: this.cfs
});
};
ngOnInit() {
this.getCourseFields(this.http);//called after the constructor and called after the first ngOnChanges()
}
getCourseFields(http: Http) {
this.http.get(`${AppSettings.API_ENDPOINT}/coursefields/list`)
// this.http.get('http://eduslim2.minedu.gov.gr/drupal/coursefields/list')
// Call map on the response observable to get the parsed people object
.map(response => <CourseField[]>response.json())
.subscribe(data => {
console.log(data);
this.courseFields = data;
for (let i = 0; i < this.courseFields.length; i++) {
this.cfs.push(new FormControl('', []));
// this.courseFields[i] = new CourseField(0,'');
}
}, // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("this.courseFields"));//run this code in all cases); */
}
/* onSubmit(studentform: any) {
let headers = new Headers({
"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
"Access-Control-Allow-Credentials": "true",
"Content-Type": "application/json",
// "Content-Type": "text/plain", // try to skip preflight
"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http.post('http://eepal.dev/drupal/entity/student', this.student, options)
// Call map on the response observable to get the parsed people object
.map((res: Response) => res.json())
.subscribe(success => {alert("Η εγγραφή έγινε με επιτυχία"); console.log("success post")}, // put the data returned from the server in our variable
error => console.log("Error HTTP POST Service"), // in case of failure show this message
() => console.log("write this message anyway"));//run this code in all cases);
} */
this._cfa.getCourseFields({});
/* addInput() {
alert('hello');
console.log(this.formGroup);
this.courseFields$ = this._ngRedux.select(state => {
console.log("in select");
for (let courseField in state.courseFields) {
this.cfs.push(new FormControl('', []));
// this.formGroup.formArray.push(this.fb.control(''));
}; */
}
return state.courseFields;
})
}
}
export class CourseField {
constructor(
public id: number,
public name: string
) {}
}
export const COURSEFIELDS_RECEIVED = 'COURSEFIELDS_RECEIVED';
export const COURSEFIELDS_SELECTED = 'COURSEFIELDS_SELECTED';
......@@ -6,6 +6,15 @@ import {
}
from '@angular/router';
import './globalstyles.css';
import { DevToolsExtension, NgRedux, select } from 'ng2-redux';
import {
IAppState,
rootReducer,
middleware,
enhancers,
} from '../store';
import { reimmutify } from '../store';
@Component({
selector: 'main',
......@@ -42,11 +51,23 @@ export default class Main {
constructor(
private router: Router,
private activatedRoute: ActivatedRoute
private activatedRoute: ActivatedRoute,
private _ngRedux: NgRedux<IAppState>,
private _devTools: DevToolsExtension
) {
router.events.subscribe((data) => {
this.path = data.url.substr(1);
});
}
const tools = _devTools.enhancer({
deserializeState: reimmutify,
});
_ngRedux.configureStore(
rootReducer,
{},
middleware,
// tools ? [ ...enhancers, tools ] : enhancers);
tools);
}
}
import {Http, Headers} from '@angular/http';
import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { ICourseField } from '../store/coursefields/coursefields.types';
import {AppSettings} from '../app.settings';
const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) };
@Injectable()
export class HelperDataService {
constructor(private http: Http) {
};
getCourseFields() {
return new Promise((resolve, reject) => {
this.http.get(`${AppSettings.API_ENDPOINT}/coursefields/list`)
.map(response => <ICourseField[]>response.json())
.subscribe(data => {
console.log(data);
resolve(data);
}, // put the data returned from the server in our variable
error => {
console.log("Error HTTP GET Service"); // in case of failure show this message
reject("Error HTTP GET Service");
},
() => console.log("this.courseFields"));//run this code in all cases); */
});
};
}
import { List } from 'immutable';
import { ICourseField, CourseFieldRecord } from './coursefields.types';
export const INITIAL_STATE = List<ICourseField>([{id: 1, name: '-'}]);
import { List, Record, fromJS } from 'immutable';
import { ICourseField, ICourseFields, CourseFieldRecord } from './coursefields.types';
import { INITIAL_STATE } from './coursefields.initial-state';
import {
COURSEFIELDS_RECEIVED,
COURSEFIELDS_SELECTED
} from '../../constants';
export function courseFieldsReducer(state: ICourseFields = INITIAL_STATE, action): ICourseFields {
switch (action.type) {
case COURSEFIELDS_RECEIVED:
return action.payload.courseFields;
case COURSEFIELDS_SELECTED: return action.payload.courseFields;
default: return state;
}
};
import { List, Map } from 'immutable';
import { ICourseFields, ICourseField, CourseFieldRecord } from './coursefields.types';
export function deimmutifyCourseFields(state: ICourseFields): Object[] {
return state.toJS();
}
export function reimmutifyCourseFields(plain): ICourseFields {
return List<ICourseField>(plain ? plain.map(CourseFieldRecord) : []);
}
import { List, Record } from 'immutable';
export interface ICourseField {
id: number;
name: string;
}
export type ICourseFields = List<ICourseField>;
export const CourseFieldRecord = Record({
id: 1,
name: '-',
});
import { ICourseField, ICourseFields } from './coursefields.types';
import { courseFieldsReducer } from './coursefields.reducer';
import { deimmutifyCourseFields, reimmutifyCourseFields } from './coursefields.transformers';
export {
ICourseField,
ICourseFields,
courseFieldsReducer,
deimmutifyCourseFields,
reimmutifyCourseFields,
};
import * as persistState from 'redux-localstorage';
import * as createLogger from 'redux-logger';
import { IAppState, rootReducer, deimmutify, reimmutify } from './store';
import { ICourseField, ICourseFields } from './coursefields/coursefields.types';
export {
IAppState,
rootReducer,
ICourseField,
ICourseFields,
reimmutify,
};
export const middleware = [
createLogger({
level: 'info',
collapsed: true,
stateTransformer: deimmutify
})
];
export const enhancers = [
persistState(
'', {
key: 'e-epal',
// serialize: s => JSON.stringify(deimmutify(s)),
serialize: s => JSON.stringify(s),
deserialize: s => reimmutify(JSON.parse(s)),
})
];
import { combineReducers } from 'redux';
import * as courseFields from './coursefields';
/*
* This is where we 'assemble' the full store out of its modules.
*/
export interface IAppState {
courseFields?: courseFields.ICourseFields;
};
export const rootReducer = combineReducers<IAppState>({
courseFields: courseFields.courseFieldsReducer,
});
export function deimmutify(state: IAppState): Object {
return {
// courseFields: courseFields.deimmutifyCourseFields(state.courseFields),
courseFields: state.courseFields,
};
}
export function reimmutify(plain): IAppState {
return plain ? {
courseFields: courseFields.reimmutifyCourseFields(plain.courseFields),
} : {};
}
......@@ -2,18 +2,20 @@
"compileOnSave": false,
"buildOnSave": false,
"compilerOptions": {
"target": "es5",
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"lib": ["es2015", "dom"]
"lib": ["es2015", "dom"],
"sourceMap": false,
"inlineSourceMap": true
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
"typings/main.d.ts",
"dist"
]
}
......@@ -22,7 +22,7 @@ module.exports = {
'@angular/common',
'@angular/router',
'@angular/http'
]
],
},
// output: {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment