相关文章推荐
玩足球的手术刀  ·  Visual Studio Code ...·  1 年前    · 
有腹肌的生菜  ·  SHOW [FULL] ...·  1 年前    · 
热心肠的长颈鹿  ·  安全开发 | Python ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm new to Redux and started with ngrx. I'm unable to understand the meaning of this line of code store.select :

 clock: Observable<Date>;
 this.clock = store.select('clock');

In very simple terms select gives you back a slice of data from the application state wrapped into an Observable.

What it means is, select operator gets the chunk of data you need and then it converts it into an Observable object. So, what you get back is an Observable that wraps the required data. To consume the data you need to subscribe to it.

Lets see a very basic example.

  • Lets define the model of our store

    export interface AppStore {
       clock: Date
    
  • Import the Store into your component from '@ngrx/store'

  • Create a store by injecting into the constructor

    constructor(private _store: Store<AppStore>){}
    
  • Select returns an Observable.

    So, declare the clock variable in your component as follows:-

    public clock: Observable<Date>;
    

    Now you can do something like follows:-

    this.clock = this._store.select('clock');
                    i tried this,  i get an observable, and if i print it i get > Store {_isScalar: false, actionsObserver: ActionsSubject, reducerManager: ReducerManager, source: Store, operator: DistinctUntilChangedOperator}  my data seems somewhere inside that observable, how do i get it from it?
    – Robdll
                    Mar 1, 2018 at 15:35
                    Kloop4: if you do not know what an obervable is, you need to look into RxJs. Please refer the official page here reactivex.io/rxjs/class/es6/Observable.js~Observable.html
    – Mav55
                    Mar 1, 2018 at 20:04
    

    Wow, this is a big topic. So basically "select" is really a RXJS operator that is used in this case to retrieve the value of a part of the application state object. So say your main app state has a array of users and a array of security functions. "Select" allows you to get a reference to a observable whose value is just that array of users. Before you get into ngrx you really need to study up on Observables and RXJS. I found this article linked off of the main Github project page for ngrx helpful.

    https://gist.github.com/btroncone/a6e4347326749f938510

    RXJS and redux can be a big topic but I suggest working on your knowledge in small bite size chunks. It took me about 2 months of working with it before I really started to feel comfortable. Even if you don't stay with ngrx, understanding how RXJS works is incredibly useful and is worth the time investment to learn it.

    Here is a gist article that also gives a good intro into RXJS. https://gist.github.com/staltz/868e7e9bc2a7b8c1f754

    Could you tell me how you took 2 months to get comfortable, i mean every developer needs such time, are you new bie, BTW nice answer – blackHawk Aug 13, 2016 at 11:46 Also i red up about select, its like map operator, takes function and transform value, is it right? – blackHawk Aug 13, 2016 at 11:48 I had a project I was working on that we were converting to Angular 2 and decided to give ngrx a go. I was new to ngrx and also to rxjs. I'd say I spent more time learning the concepts of rxjs and how observables work than ngrx. Most of what took time for me grasp with ngrx was what are the best conventions setting up reducers and the flow logic. How to set up action creators. I took heavy inspiration for the project set up from the example app linked off of the ngrx store project readme. github.com/ngrx/example-app – wiredprogrammer Aug 13, 2016 at 12:22 Being able to understand what was going on in the example app took a bit of time. I also got a egghead subscription and watched redux videos made by the creator Dan Abrimov. Did some reading of popular questions on the redux project issues. – wiredprogrammer Aug 13, 2016 at 12:24 I've been a programmer for about 15 years but I've only gotten into the JavaScript side of it in about the last 5 and only started learning about the frameworks in the last 2 or 3 years. I'm a bit late to the framework scene. – wiredprogrammer Aug 13, 2016 at 12:36

    It returns the state called 'clock'.

    Here is an example. In the constructor store.select is called, this time with 'todos'.

    https://github.com/btroncone/ngrx-examples/blob/master/todos/src/app/todo-app.ts

    export class TodoApp {
        public todosModel$ : Observable<TodoModel>;
        //faking an id for demo purposes
        private id: number = 0;
        constructor(
            private _store : Store<AppState>
            const todos$ = _store.select<Observable<Todo[]>>('todos');
            const visibilityFilter$ = _store.select('visibilityFilter');
    

    In the bootstrap, provideStore is given APP_REDUCERS

    import {bootstrap} from '@angular/platform-browser-dynamic';
    import {TodoApp} from './todo-app';
    import {provideStore} from "@ngrx/store";
    import * as APP_REDUCERS from "./reducers/reducers";
    export function main() {
      return bootstrap(TodoApp, [
          provideStore(APP_REDUCERS)
      .catch(err => console.error(err));
    

    APP_REDUCERS is all the reducers defined. The todos reducer is defined as follows:

        import {ActionReducer, Action} from "@ngrx/store";
    import {Todo} from "../common/interfaces";
    import {ADD_TODO, REMOVE_TODO, TOGGLE_TODO} from "../common/actions";
    export const todos : ActionReducer<Todo[]> = (state : Todo[] = [], action: Action) => {
      switch(action.type) {
          case ADD_TODO:
              return [
                  ...state,
                  action.payload
    

    There are a few ways to do this, and you can compose a list of all your reducers, essentially defining a series of object keys that refer to a reducer object.

    Store.select returns an observable that you can subscribe to either in your component or template via '|async'.

    This.store.select('keyname') will return the data from store object of 'keyname' property has. you can further look for inner object in store using multiple reducer with StoreModule.forFeature("master", masterReducer) in main module with createSelector

    export const getMasterState = createFeatureSelector<myModels.MasterState>('master');
    export const getMatserBranchList = createSelector(
        getMasterState,
        (state: myModels.MasterState): myModels.Branch[] => state.branchList
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.

  •