简体   繁体   English

用NGRX改变状态后如何执行一些代码?

[英]How to execute some code after changing state with NGRX?

I'm developing an app with Angular 2.0 and NGRX. 我正在开发一个使用Angular 2.0和NGRX的应用程序。 I've come from React/Redux, so I'm still figuring out how to do some things. 我来自React / Redux,所以我还在想办法做些什么。

When I want to print something inside the template I can write something like this: 当我想在模板中打印一些东西时,我可以这样写:

@Component({
  selector: 'dashboard',
  directives: [MainContainer],
  styleUrls: [
    './dashboard.style.css'
  ],
  template: `
    <main-container [section]="viewSection | async"></main-container>
  `
})
export class Dashboard {

  private viewSection: Observable<MainViewSection>;

  constructor(
    private store: Store<AppState>
  ) {
    this.viewSection = this.store.let(getMainViewSection());
  }

}

But now I want to execute some code after a value changes (it will use store's values as an input (that will change the view afterwards) 但现在我想在值更改后执行一些代码(它将使用商店的值作为输入(之后将更改视图)

I know that I can do it with componentWillReceiveProps in React. 我知道我可以在React中使用componentWillReceiveProps

The only thing that I've found that can be usefull is something like this: 我发现的唯一有用的东西是这样的:

export class View {

  constructor(
    private store: Store<AppState>
  ) {
    this.store.select('data').subscribe((val: DataState) => {
      if (!layer) {
        return;
      }
      layer.setData(val);
    });
  }

}

I don't think that's an elegant way, but I cannot figure out another way.. People has told me to use services (I don't know how that fits on this case) and I've read about @Effects , but I don't know if it's what I'm looking for. 我不认为这是一种优雅的方式,但我无法想出另一种方式......人们告诉我使用服务(我不知道这是怎么适合这种情况)而且我已经阅读了@Effects ,但我不知道这是不是我在找什么。

Thanks! 谢谢!

I think @Effect is definitely what you are looking for. 我认为@Effect肯定是你想要的。 An @Effect executes when a certain state action gets called. @Effect某个状态操作时会执行@Effect Take this example from the official NgRx example app 以官方NgRx 示例应用程序为例

  @Effect() clearSearch$ = this.updates$
    .whenAction(BookActions.SEARCH)
    .map<string>(toPayload)
    .filter(query => query === '')
    .mapTo(this.bookActions.searchComplete([]));

Using the whenAction method you specify which action triggers the effect. 使用whenAction方法指定触发效果的操作。 In this example they use toPayload which returns only the payload of the executed action. 在此示例中,它们使用toPayload ,它仅返回已执行操作的有效内容。 But you have access to the entire state of the application. 但您可以访问应用程序的整个状态。

This is how you could use it for example: 这就是你如何使用它的例子:

    .whenAction(YourActions.SOMETHING)
    .switchMap(data => this._xhr.send(data.state.yourData) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM