gpt4 book ai didi

javascript - 使用 NGRX 更改状态后如何执行一些代码?

转载 作者:太空狗 更新时间:2023-10-29 18:33:40 26 4
gpt4 key购买 nike

我正在使用 Angular 2.0 和 NGRX 开发应用。我来自 React/Redux,所以我仍在弄清楚如何做一些事情。

当我想在模板中打印一些东西时,我可以这样写:

@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());
}

}

但现在我想在值更改后执行一些代码(它将使用商店的值作为输入(之后将更改 View )

我知道我可以在 React 中使用 componentWillReceiveProps 来完成。

我发现唯一有用的东西是这样的:

export class View {

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

}

我不认为这是一种优雅的方式,但我想不出另一种方式。人们告诉我使用服务(我不知道这如何适合这种情况)并且我已经阅读了 @Effects ,但我不知道这是否是我要找的。

谢谢!

最佳答案

我认为 @Effect 绝对是您要找的。 @Effect 在调用特定状态操作时执行。从官方 NgRx 拿这个例子 example app

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

使用 whenAction 方法,您可以指定触发效果的操作。在此示例中,他们使用 toPayload,它仅返回已执行操作的有效负载。但是您可以访问应用程序的整个状态。

例如,您可以这样使用它:

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

关于javascript - 使用 NGRX 更改状态后如何执行一些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38623609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com