ngrx - chain two store.select slices

后端 未结 3 1617
逝去的感伤
逝去的感伤 2021-02-13 21:00

In my Todo Cmp I have this code

this.todoListGroup$ = this.ngrx.select(fromRoot.getTodos)
    .flatMap((todos: Todo[]) => {
        console.log(todos)
                


        
3条回答
  •  既然无缘
    2021-02-13 21:50

    Would something like this work:

    this.todoListGroup$ =
        Observable.combineLatest(
            this.ngrx.select(fromRoot.getTodos), 
            this.ngrx.select(fromRoot.getLastChangedTodo)
        )
        .do(([todos, lastToDo]) => console.log(todos, lastToDo));
    

    The do would execute each time either one of getTodos or getLastChangedTodo is updated and would take the latest known values from each of them at the time of the update. The caveat here is the order of when each of those updates are fired may not always be the same. So, if you wanted more of a chained (or cascaded) update then you could do this:

    this.todoListGroup$ =
        this.ngrx.select(fromRoot.getTodos)
        .withLatestFrom(this.ngrx.select(fromRoot.getLastChangedTodo))
        .do(([todos, lastToDo]) => console.log(todos, lastToDo));
    

    That will execute each time getToDos is updated and would take the latest value from getLastChangedTodo. Hence the chained (or cascaded) updated idiom.

    edit for rxjs 5+ syntax:

    this.todoListGroup$ =
        combineLatest(
            this.ngrx.select(fromRoot.getTodos), 
            this.ngrx.select(fromRoot.getLastChangedTodo)
        )
        .pipe(tap(([todos, lastToDo]) => console.log(todos, lastToDo)));
    
    
    this.todoListGroup$ =
        this.ngrx.select(fromRoot.getTodos).pipe(
          withLatestFrom(this.ngrx.select(fromRoot.getLastChangedTodo)),
          tap(([todos, lastToDo]) => console.log(todos, lastToDo))
        );
    

提交回复
热议问题