头图

Store

state.ts

Defines the State data model related to the Site Context business.

The routine for defining a data model is:

 export const SITE_CONTEXT_FEATURE = 'siteContext';

export interface StateWithSiteContext {
  [SITE_CONTEXT_FEATURE]: SiteContextState;
}

This is the top-level State model.

SiteContextState contains three sub-States:

 export interface SiteContextState {
  languages: LanguagesState;
  currencies: CurrenciesState;
  baseSite: BaseSiteState;
}

Taking CurrencyState as an example, it not only contains the list of Entities, but also the Currency of the current Active state:

 export interface CurrenciesState {
  entities: CurrencyEntities;
  activeCurrency: string;
}

Define the Entities list again:

 export interface CurrencyEntities {
  [isocode: string]: Currency;
}

The above is the State data structure required by the Site Context field.

Note the use of SITE_CONTEXT_FEATURE, in addition to defining feature state in this file, it is also used in the following two files:

Scenario 1: Used to create a feature selector:

Scenario 2: Register the store with StoreModule.forFeature:

When using the createSelector and createFeatureSelector functions, @ngrx/store keeps track of the latest parameters for calling the selector function. Because selectors are pure functions, the last result can be returned when the arguments match without re-calling the selector function. This can provide performance benefits, especially for selectors that perform expensive computations. This practice is called memoization .

createFeatureSelector is a convenience method that returns ---0598a5d5c9e28527274e93508aa7acf6 Feature State of the top level ( Top Level ). It returns a typed ( typed ) selector function for the state's feature slice ( Feature Slice ).

Note that there are two ways to write the call to createFeatureSelector.

Writing 1

Figure 2 below must be a slice of 1, and the type of 3 must be the same as the type of 2:

The position of 2 is actually the position of the result:

Writing 2

 import { createSelector, createFeatureSelector } from '@ngrx/store';
 
export const featureKey = 'feature';
 
export interface FeatureState {
  counter: number;
}
 
export interface AppState {
  feature: FeatureState;
}
 
export const selectFeature = createFeatureSelector<AppState, FeatureState>(featureKey);
 
export const selectFeatureCount = createSelector(
  selectFeature,
  (state: FeatureState) => state.counter
);

I have done tests, and in the SAP e-commerce cloud Spartacus UI project, the two writing methods are completely equivalent:

It can be compiled successfully:


注销
1k 声望1.6k 粉丝

invalid