Last active
May 17, 2018 04:23
-
-
Save taylorc/83ae26afee1a8ce3586e218a33f69de8 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
| import { HttpClient, HttpHeaders } from '@angular/common/http'; | |
| import { Action, Selector, State, StateContext } from '@ngxs/store'; | |
| import { FetchPosts } from './post.actions'; | |
| export interface PostStateModel { | |
| posts: Post[]; | |
| loading: boolean; | |
| } | |
| @State<PostStateModel>({ | |
| name: 'posts', | |
| defaults: { | |
| posts: [], | |
| loading: true | |
| } | |
| }) | |
| export class PostState { | |
| /** | |
| * | |
| */ | |
| constructor(private http: HttpClient) { } | |
| @Selector() | |
| public static loading(state: PostStateModel) { | |
| return state.loading; | |
| } | |
| @Selector() | |
| public static posts(state: PostStateModel) { | |
| return state.posts; | |
| } | |
| @Action(FetchPosts) | |
| getPosts({ getState, setState }: StateContext<PostStateModel>) { | |
| const state = getState(); | |
| let posts: Post[] = []; | |
| this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts').subscribe(post => { | |
| posts = post; | |
| console.log(posts[0].id); | |
| setState({ | |
| ...state, | |
| posts: posts, | |
| loading: false | |
| }); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment