Angular, NGRX, как использовать оператор rx js в ngOnInit - PullRequest
1 голос
/ 04 февраля 2020

Angular, NGRX, как использовать оператор rx js в ngOnInit

Эй,

У меня небольшая проблема, чтобы понять операторы объединения rx js с ngrx. Ниже у меня есть простой компонент с хранилищем ngrx - там у меня есть все необходимые данные и селекторы работают должным образом:

export class TestComponent implements OnInit {

    selector1$: Observable<any>;
    selector2$: Observable<any>;



    constructor(private store$: Store<StoreModel>) {
    }

    ngOnInit() {

    selector1$ = this.store$.pipe(select(selectValue1));
    selector2$ = this.store$.pipe(select(selectValue1));
    }

}

Но - я бы хотел использовать операторы rx js - например, с помощью withLatestFrom и вызова там 2 селектора - с чего мне начинать .pipe?

I.

ngOnInit() {

    pipe(
            withLatestFrom(
                this.store$.pipe(select(selectValue1));
                this.store$.pipe(select(selectValue2));
            ),
            map(([respValue1, respValue2]) => {
               }
    }

II. Или через этот магазин $.

this.store$.pipe(
            withLatestFrom(
                this.store$.pipe(select(selectValue1));
                this.store$.pipe(select(selectValue2));
            ),
            map(([respValue1, respValue2]) => {
           }
        }

III. или как I./II. но по стрелке?

this.store$.pipe(combineLatest(
                this.store$.pipe(select(selectValue1)),
                this.store$.pipe(select(selectValue2)),
            (respValue1, respValue2) => {
                return `${respValue1} + ${respValue2}`

            })).subscribe(console.log);

Все решения не работают. Я должен создать новое наблюдаемое значение для вызова операторов RX js? Или какое решение лучше для этого случая.

Заранее спасибо.

Ответы [ 3 ]

1 голос
/ 04 февраля 2020

withLatestFrom() не является "Наблюдаемым методом создания", поэтому вы, вероятно, захотите использовать вместо него combineLatest() (также withLatestFrom() работает не так, как combineLatest()).

combineLatest([
  this.store$.pipe(select(selectValue1)),
  this.store$.pipe(select(selectValue1)),
]).subscribe(([result1, result2]) => {
  // do whatever you want here
})
1 голос
/ 04 февраля 2020
ngOnInit() {
    combineLatest(
        this.store$.pipe(select(selectValue1)),
        this.store$.pipe(select(selectValue2))
    ).subscribe(console.log);
}

Редактировать:

ngOnInit() {
    combineLatest(
        this.store$.pipe(select(selectValue1)),
        this.store$.pipe(select(selectValue2))
    ).pipe(tap(console.log))
        .subscribe()
}
0 голосов
/ 04 февраля 2020

Почему бы не сохранить простоту и объединить селекторы с createSelector? Это также приведет к меньшему количеству обнаруженных изменений.

export const selectValueOneAndTwo = createSelector(
  selectValue1, 
  selectValue2,
  (one, two) => one + two
)
ngOnInit() {
    selector$ = this.store$.pipe(select(selectValueOneAndTwo));
}
...