Angular 2 update global state as a side effect of updating a certain state

拥有回忆 提交于 2019-11-28 02:02:40
cartant

Storing an isLoading indicator in a central place is a similar to what is sometimes done with error information. One solution for storing a central error involves using a reducer that ignores actions' types and looks only to see if they contain an error property.

If you were to adopt a suitable naming scheme for your effects' action types, you could do much the same thing with isLoading.

One possible naming scheme could be:

SOME_ACTION_REQUEST
SOME_ACTION_RESPONSE
SOME_ACTION_ERROR

With such a scheme, the following reducer would examine the action types and set the isLoading state accordingly:

export function isLoadingReducer(state: boolean = false, action: Action): boolean {

    if (/_REQUEST$/.test(action.type)) {
        return true;
    } else  if (/(_RESPONSE|_ERROR)$/.test(action.type)) {
        return false;
    } else {
        return state;
    }
}

Using a boolean value for isLoading assumes that you would not have concurrent asynchronous effects, so if that's an issue, you could extend the reducer to use a counter instead.

If you wire things up this way, the isLoading indicator doesn't need to know anything about individual effects and vice versa.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!