Angular, NgRx how to use RxJS operator in ngOnInit

Issue

I have a small problem to understand combine RxJS operators with NgRx. Below I have a simple component with NgRx store – there I have all necessary data and the selectors are working properly:

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));
    }

}

But – I would like to using RxJS operators – for example using withLatestFrom and calling there 2 selectors – where I should start .pipe?

I.

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

II. Or by this.store$:

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

III. or like I./II. but using arrow?

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

All of the solutions are not working. I should create new observable value for calling RxJS operators? Or what is the best solution for that case.

Thank you in advance.

Solution

withLatestFrom() is not an “Observable creation method” so you’ll probably want to use combineLatest() instead (also, withLatestFrom() works differently than combineLatest()).

combineLatest([
  this.store$.pipe(select(selectValue1)),
  this.store$.pipe(select(selectValue1)),
]).subscribe(([result1, result2]) => {
  // do whatever you want here
})

Answered By – martin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published