Created
May 8, 2020 07:16
-
-
Save hijiangtao/d4def77867ff4aec2740ba6ab83b24bf to your computer and use it in GitHub Desktop.
Demo of using @ngrx/effects to load data from http request
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 { 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 | |
) {} | |
} |
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
@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' }); | |
} | |
} |
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
@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