Skip to content

Instantly share code, notes, and snippets.

@hijiangtao
Created May 8, 2020 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hijiangtao/d4def77867ff4aec2740ba6ab83b24bf to your computer and use it in GitHub Desktop.
Save hijiangtao/d4def77867ff4aec2740ba6ab83b24bf to your computer and use it in GitHub Desktop.
Demo of using @ngrx/effects to load data from http request
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { EMPTY } from 'rxjs';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { MoviesService } from './movies.service';
@Injectable()
export class MovieEffects {
loadMovies$ = createEffect(() => this.actions$.pipe(
ofType('[Movies Page] Load Movies'),
mergeMap(() => this.moviesService.getAll()
.pipe(
map(movies => ({ type: '[Movies API] Movies Loaded Success', payload: movies })),
catchError(() => EMPTY)
))
)
);
constructor(
private actions$: Actions,
private moviesService: MoviesService
) {}
}
@Component({
template: `
<div *ngFor="let movie of movies$ | async">
{{ movie.name }}
</div>
`
})
export class MoviesPageComponent {
movies$: Observable<Movie[]> = this.store.select(state => state.movies);
constructor(private store: Store<{ movies: Movie[] }>) {}
ngOnInit() {
this.store.dispatch({ type: '[Movies Page] Load Movies' });
}
}
@Component({
template: `
<li *ngFor="let movie of movies">
{{ movie.name }}
</li>
`
})
export class MoviesPageComponent {
movies: Movie[];
constructor(private movieService: MoviesService) {}
ngOnInit() {
this.movieService.getAll().subscribe(movies => this.movies = movies);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment