如何从ngrx存储中获取数据并将其更新到Observable变量中?

时间:2019-03-28 20:42:22

标签: angular ecmascript-6 store ngrx ngrx-store

我有一个非常简单的功能模块,其中包含由@ ngrx / schematics创建的store / reducers / etc。在此功能模块中,我有2个组件-表单和项目列表,默认情况下为空,您可以通过表单添加项目。当我通过表单操作添加某些东西时,reducer获取有效负载,但第二个组件中的项目列表未更新。

商品列表html:

<section class="sub-list">
  <div class="container">
    <header class="sub-list--header"><h1>My Subscriptions</h1></header>
    <span *ngIf="length$ | async">Subscriptions count - {{ length$ | async }}</span>
    <main class="sub-list--content" *ngIf="list$ | async as list">
      <div class="sub-list--item" *ngFor="let item of list">
        <div class="name">{{ item.name }}</div>
      </div>
    </main>
  </div>
</section>

商品列表组件:

import { Component, OnInit } from '@angular/core';
import { MatSnackBar } from '@angular/material';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';

// Store
import * as fromSub from '../../reducers/subscription.reducer';
import * as subActions from '../../actions/subscription.actions';
// Models
import { Subscription } from '../../models/Subscription';

@Component({
  selector: 'app-sub-list',
  templateUrl: './sub-list.component.html',
  styleUrls: ['./sub-list.component.scss']
})
export class SubListComponent implements OnInit {
  list$: Observable<Subscription[]>;
  length$: Observable<number>;
  constructor(
    private snackBar: MatSnackBar,
    private subStore: Store<fromSub.State>
  ) {
    this.list$ = this.subStore.select('subscriptionsList');
    this.length$ = this.subStore.select('length');
  }

  ngOnInit() {
  }

}

表单组件(以防万一我没有正确分配动作):

import { Component, OnInit } from '@angular/core';
import { MatSnackBar } from '@angular/material';
import { Store } from '@ngrx/store';

// Store
import * as fromSub from '../../reducers/subscription.reducer';
import * as subActions from '../../actions/subscription.actions';
// Models
import { Subscription } from '../../models/Subscription';

@Component({
  selector: 'app-sub-form',
  templateUrl: './sub-form.component.html',
  styleUrls: ['./sub-form.component.scss']
})
export class SubFormComponent implements OnInit {
  name: string;
  price: number;
  link: string;
  date: Date;
  constructor(
    private snackBar: MatSnackBar,
    private subStore: Store<fromSub.State>
  ) {
    this.price = 0;
  }

  ngOnInit() {
  }

  addSubscription = (): void => {
    // Snackbar test
    if (!this.name) {
      this.snackBar.open('Name field is empty', 'Close', { duration: 3000 });
      return;
    }
    // if (this.link === '') {}
    if (this.price < 0) {
      return;
    }
    if (!this.date) {
      this.snackBar.open('Date field is empty', 'Close', { duration: 3000 });
      return;
    }
    const newSub: Subscription = {
      name: this.name,
      price: this.price,
      link: this.link,
      date: this.date,
    };
    this.subStore.dispatch(new subActions.AddSubscription(newSub));
    this.snackBar.open('Subscription added', 'Close', { duration: 3000 });
  }
}

模块减速器:

import { SubscriptionActions, SubscriptionActionTypes } from '../actions/subscription.actions';
import { Subscription } from '../models/Subscription';

export interface State {
  length: number;
  subscriptionsList: Subscription[];
}

export const initialState: State = {
  length: 0,
  subscriptionsList: [],
};

export function reducer(state = initialState, action: SubscriptionActions): State {
  switch (action.type) {

    case SubscriptionActionTypes.LoadSubscriptions:
      return state;

    case SubscriptionActionTypes.AddSubscription:
      return Object.assign({}, state, {
        subscriptionsList: state.subscriptionsList.concat(action.payload),
        length: state.subscriptionsList.length + 1
      });

    default:
      return state;
  }
}

所以这可能是化简版(错误的商店更新)或组件(错误的选择或错误的提供者)

的问题。

1 个答案:

答案 0 :(得分:0)

首先想到的是

您的全球商店如下:

interface RootStore {
  subscription: {
    subscriptionsList: Array<...>,
    length: number;
  }
}

因此,当您想获得this.lenght$组件时,您必须这样做:

this.lenght$ = this.store.select(rootStore => rootStore.subscription.lenght)

当您订阅组件中的存储时,您尝试获取RootStore上的length密钥。它不存在,因此您正在订阅undefined。分派操作后,它仍然是未定义的,因此您的组件没有刷新数据。