@ ngrx/store订阅商店的一部分,并避免检测到对其他部分的更改 [英] @ngrx/store subscription to part of a store and avoid detecting changes to other parts

查看:61
本文介绍了@ ngrx/store订阅商店的一部分,并避免检测到对其他部分的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我商店中的一个化简工具处理应用程序中选择的事物.该商店的界面(简称为app)如下所示:

One of the reducers in my store deals with things that are selected within the app. The interface for this store (let's called it app) could look like this:

interface IApp {
    selectedProject: IProject;
    selectedPart: IPart;
}

因此,我希望有一个仅在选择了不同的项目"时才执行操作的订阅.我写了这样的东西:

So I want to have a subscription that performs an action only when a different 'project' is selected. I wrote something like this:

this.store.select('app')
    .map((store: IApp) => store.selectedProject)
    .subscribe((project: IProject) => {
        // Stuff happens here
    });

selectedProject更改时,此函数会填充.但是,当selectedPart更改时,它也会填充.显然,无论映射如何,它都会监听整个app存储.那是有道理的.

This function does it stuff when selectedProject changes. However, it also does it stuff when selectedPart changes. Clearly, it listens to the whole of the app store, regardless of the map. That makes sense.

问题

我不希望这种情况发生.我只希望我的函数在selectedProject更改时执行.

I don't want this to happen. I only want my function to execute when selectedProject changes.

我知道我可以将selectedProjectselectedPart拆分到不同的商店中以解决此问题.但是,我很快就会拥有许多商店.也许就这样吧?

I know I can split selectedProject and selectedPart into different stores to solve this. However, I could quickly end up with many, many stores. Maybe this the way it is meant to be?

还有其他方法吗?我可以使用此界面保留商店,并订阅仅检测商店的selectedProject部分的更改吗?

Is there another way though? Can I keep the store with this interface and have a subscription that only detects changes to the selectedProject part of the store?

推荐答案

我相信您正在寻找

I believe you are looking for distinctKeyUntilChanged.

this.store.select('app')
  //Only emit when selectedProject has changed
  .distinctUntilKeyChanged(
    //Key to filter on
    'selectedProject',
    //Optional comparison function if you have a specific way of comparing keys 
    (x, y) => x.projectName === y.projectName)
  .pluck('selectedProject')
  .subscribe((project: IProject) => {});

这篇关于@ ngrx/store订阅商店的一部分,并避免检测到对其他部分的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆