1 | import { HttpErrorResponse } from '@angular/common/http';
|
---|
2 | import { Injectable } from '@angular/core';
|
---|
3 | import { Action, Store } from '@ngrx/store';
|
---|
4 | import { Observable, throwError } from 'rxjs';
|
---|
5 | import { catchError, filter, map } from 'rxjs/operators';
|
---|
6 |
|
---|
7 | import { QuestionStateViewModel } from 'src/app/shared-app/models';
|
---|
8 | import { EffectStartedWorking, GetQuestionState } from './question-state/question.actions';
|
---|
9 | import { questionStateQuery } from './question-state/question.selectors';
|
---|
10 | import { QuestionState } from './question-state/question.state';
|
---|
11 |
|
---|
12 | @Injectable({
|
---|
13 | providedIn: 'root'
|
---|
14 | })
|
---|
15 | export class QuestionFacadeService {
|
---|
16 | effectWorking$: Observable<boolean | HttpErrorResponse>;
|
---|
17 |
|
---|
18 | constructor(private store: Store<QuestionState>) {
|
---|
19 | this.effectWorking$ = this.store.select(questionStateQuery.effectWorking).pipe(
|
---|
20 | filter((effect) => effect !== null),
|
---|
21 | map((effect) => {
|
---|
22 | if (effect instanceof HttpErrorResponse) {
|
---|
23 | throw effect;
|
---|
24 | } else {
|
---|
25 | return effect;
|
---|
26 | }
|
---|
27 | }),
|
---|
28 | catchError((err) => {
|
---|
29 | return throwError(err);
|
---|
30 | })
|
---|
31 | );
|
---|
32 | }
|
---|
33 |
|
---|
34 | public getQuestion(): Observable<QuestionStateViewModel> {
|
---|
35 | return this.store
|
---|
36 | .select(questionStateQuery.getQuestion)
|
---|
37 | .pipe(filter((x: QuestionStateViewModel | null): x is QuestionStateViewModel => x !== null));
|
---|
38 | }
|
---|
39 |
|
---|
40 | public fetchQuestion(questionUid: string): void {
|
---|
41 | this.dispatchEffect(new GetQuestionState(questionUid));
|
---|
42 | }
|
---|
43 |
|
---|
44 | private dispatch(action: Action): void {
|
---|
45 | this.store.dispatch(action);
|
---|
46 | }
|
---|
47 |
|
---|
48 | private dispatchEffect(action: Action): void {
|
---|
49 | this.dispatch(new EffectStartedWorking());
|
---|
50 | this.dispatch(action);
|
---|
51 | }
|
---|
52 | }
|
---|