Как добавить эффект с идентификатором в ngrx Store - PullRequest
0 голосов
/ 16 мая 2019

Я впервые в Ngrx Store и хочу использовать его для получения публикаций из моей базы данных.Я могу сделать это для простой публикации, но сейчас я хочу сделать это, но для специального идентификатора

Это мой эффект

  @Effect()
  getPiinsByProfilesEffect$: Observable<Action> = this.actions$
    .pipe(
      ofType<featureActions.GetPiinsByProfile>(featureActions.ActionTypes.GET_PIINS_BY_PROFILE),
      startWith(new featureActions.GetPiinsByProfile()),
      switchMap(action => this.dataService.GetPiinsByProfile(action.id)
        .pipe(
          map(items => new featureActions.GetPiinsByProfileSuccess(items.results)),
          catchError(error =>
            observableOf(new featureActions.GetPiinsByProfileFail(error))
          )
        )
      )
    );

Это мой сервис

  GetPiinsByProfile(id: string): Observable<ListPiinsResponse> {
    const limit = '7';
    const page = '1';

    return this.http.get<ListPiinsResponse>(`${this.baseUrl}/piins/profile/${id}`, {
      params: {
        limit: limit, page
      }
    });
  }

И это мое действие

export class GetPiinsByProfile implements Action {
  readonly type = ActionTypes.GET_PIINS_BY_PROFILE;
  constructor(public id: String) { }
}

export class GetPiinsByProfileStart implements Action {
  readonly type = ActionTypes.GET_PIINS_BY_PROFILE_START;
}

export class GetPiinsByProfileFail implements Action {
  readonly type = ActionTypes.GET_PIINS_BY_PROFILE_FAIL;

  constructor(public payload: any) { }
}

export class GetPiinsByProfileSuccess implements Action {
  readonly type = ActionTypes.GET_PIINS_BY_PROFILE_SUCCESS;

  constructor(public payload: Piins[]) { }
}

Спасибо всем, если вы можете мне помочь:)

Ответы [ 2 ]

0 голосов
/ 17 мая 2019

Спасибо всем, и я нахожу решение.

Я использую тот же конструктор, что и @vishnu, но настоящая проблема была в моем влиянии. Это моя новая версия:

  @Effect()
  getPiinsByProfilesEffect$: Observable<ActionsPiins> = this.actions$
    .pipe(
      ofType<featureActions.GetPiinsByProfile>(featureActions.ActionTypes.GET_PIINS_BY_PROFILE),
      startWith(new featureActions.GetPiinsByProfileLoad),
      switchMap(action => {
        console.log(action);
        if (action.type === featureActions.ActionTypes.GET_PIINS_BY_PROFILE) {
          const getPiinsByProfileAction = action as featureActions.GetPiinsByProfile;
          return this.dataService.GetPiinsByProfile(getPiinsByProfileAction.id)
            .pipe(
              tap((list) => console.log(list)),
              map(items => new featureActions.GetPiinsByProfileSuccess(items.results)),
              catchError(error =>
                observableOf(new featureActions.GetPiinsByProfileFail(error))
              )
            );
        } else {
          return observableOf(action);
        }

      }
      )
    );

А это мое новое действие:

export class GetPiinsByProfileLoad implements Action {
  readonly type = ActionTypes.GET_PIINS_BY_PROFILE_LOAD;
}
0 голосов
/ 17 мая 2019

В вашем компоненте вы должны отправить действие, чтобы получить публикацию на основе идентификатора.

Так и должно быть

export class ABC {
    constructor(public store: Store<>,
               public action: PiinsAction) { }
      ngOnInit() {
         this.store.dispatch(this.action.GetPiinsByProfile(id));
     }
}

Вам также необходимо подписать результат с помощью селекторов.

https://ultimatecourses.com/blog/ngrx-store-understanding-state-selectors

...