Skip to content

Instantly share code, notes, and snippets.

@taylorc
Last active May 17, 2018 04:23
Show Gist options
  • Select an option

  • Save taylorc/83ae26afee1a8ce3586e218a33f69de8 to your computer and use it in GitHub Desktop.

Select an option

Save taylorc/83ae26afee1a8ce3586e218a33f69de8 to your computer and use it in GitHub Desktop.
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