Last active
April 24, 2018 12:30
-
-
Save izaacdb/ae79a0c3a57929e9578cd7511cb91565 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reducer | |
export const examples = (state: any = [], {type, payload}) => { | |
switch (type) { | |
case 'ADD_EXAMPLES': | |
console.log(state); | |
return payload; | |
case 'CREATE_EXAMPLES': | |
return [...state, payload]; | |
case 'UPDATE_EXAMPLES': | |
return state.map(example => { | |
return example.token === payload.token ? Object.assign({}, example, payload) : example; | |
}); | |
case 'DELETE_EXAMPLES': | |
return state.filter(example => { | |
return example.token !== payload.token; | |
}); | |
default: | |
return state; | |
} | |
}; | |
// Module import | |
imports : [ | |
StoreModule.forRoot({ | |
examples | |
}) | |
] | |
// Interface for store | |
export interface AppStore { | |
examples: Example[]; | |
something: String[]; | |
} | |
// Store service | |
@Injectable() | |
export class StoreService { | |
examples: Observable<Example[]>; | |
constructor( | |
private http: HttpClient, | |
private appStore: Store<AppStore> | |
) { | |
this.examples = appStore.select(store => store.examples); | |
} | |
getSentences(paras: number = 5, filterText = '') { | |
const apiUrl = `https://baconipsum.com/api/?type=meat-and-filler¶s=${paras}&format=json`; | |
return this.http.get(apiUrl) | |
.map(res => { | |
return Object.values(res) | |
.filter(item => item.includes(filterText)) | |
.map((item, i) => new Example(item, i)); | |
}) | |
.map((payload: Example[]) => { | |
console.log('payload', payload); | |
return {type: 'ADD_EXAMPLES', payload}; | |
}) | |
// Create the action and dispatch it to update the selected store | |
.subscribe((action) => { | |
console.log('action', action); | |
this.appStore.dispatch(action); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment