在使用 ngrx 时完成调度后执行代码 [英] Executing code after dispatch is completed while using ngrx

查看:54
本文介绍了在使用 ngrx 时完成调度后执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的示例 Angular 2 应用程序中,我使用 ngrx/store 和 ngrx/effects 进行状态管理.

In my sample Angular 2 application , I am using ngrx/store and ngrx/effects for state management.

下面是组件中添加新项目的功能之一.

Below is one of the function in a component to add a new item.

addAuthor() {

    this.store.dispatch(addAuthorAction(this.fg.value));
    console.log('2')        
} 

在上面的代码中this.store.dispatch(addAuthorAction(this.fg.value));"负责对服务器进行 AJAX 调用并将新作者添加到数据库,工作正常.

In the above code "this.store.dispatch(addAuthorAction(this.fg.value));" takes care of making an AJAX call to server and adding a new author to database, which is working fine.

因为this.store.dispatch(addAuthorAction(this.fg.value));"是一个异步操作,即使在 AJAX 调用之前,console.log("2") 语句也会被执行完成.

And because "this.store.dispatch(addAuthorAction(this.fg.value));" is an async action , console.log("2") statement gets executed even before the AJAX call is completed.

我的问题是,需要修改什么才能在 store.dispatch 完成后执行 console.log.

My question is , what needs to be modified so that console.log gets executed after store.dispatch is done.

推荐答案

快速回答:你不能.

正如你所说,dispatch 是异步的.

As you said, dispatch is asynchronous.

你应该做的是使用@ngrx/effects.它与使用 addAuthorAction 几乎相同,不同之处在于您捕获"了函数而不是调用函数.分派的动作,并在它们被减速器应用后做一些事情.

What you should do is use @ngrx/effects. It's nearly the same as using addAuthorAction except that instead of calling a function, you "catch" the dispatched actions and do something just after they've been applied by the reducers.

所以我通常做的是将我的动作分成 3 个,例如:

So what I do in general, is that I divide my actions in 3, for example :

  • FETCH_USER

FETCH_USER_SUCCESS

FETCH_USER_ERROR

FETCH_USER 仅用于切换布尔值,因此我可以在获取用户时显示微调器

FETCH_USER is just used to toggle a boolean so I can display a spinner while fetching the user

我从一个 effect 中捕捉到这个动作并发出一个 http 请求来获取用户

I catch this action from an effect and make an http request to fetch the user

如果 http 响应正常并且我有我正在寻找的信息,我从效果 FETCH_USER_SUCCESS 发送响应作为有效负载,否则我发送 FETCH_USER_ERROR 然后我将布尔值切换为 false(例如,我们可以尝试再次获取他).

If the http response is OK and I have the info I'm looking for, I dispatch from the effect FETCH_USER_SUCCESS with the response as payload, otherwise I dispatch FETCH_USER_ERROR and I toggle the boolean to false (so we can try to fetch him again for example).

因此,在您的示例中,如果您想在 FETCH_USER_SUCCESS 之后 console.log 某些内容,只需使用另一种效果来捕获 FETCH_USER_SUCCESS 并在此处执行您想做的操作.

So in your example, if you want to console.log something AFTER the FETCH_USER_SUCCESS, just use another effect to catch the FETCH_USER_SUCCESS and do what you want to here.

这篇关于在使用 ngrx 时完成调度后执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆