代码之家  ›  专栏  ›  技术社区  ›  Rich Duncan

注销时重置应用程序状态

  •  0
  • Rich Duncan  · 技术社区  · 8 年前

    我有一个应用程序,它为应用程序中的许多主题领域提供了状态类。比如说它是一个聊天应用程序,主题是用户、聊天信息和聊天室。用户通过登录进行身份验证/授权。从那里,状态取决于登录的用户。当用户注销时,应用程序需要将所有“主题”的状态重置为其默认状态。

    问题:

    1. 组织这些州最好的方法是什么?子状态的用法似乎不错,但子状态文档讨论了如何设置子状态,但没有显示任何有关状态“绑定”含义的示例。
    2. 如何重置所有状态?这是重置API的良好用法吗?
    2 回复  |  直到 7 年前
        1
  •  1
  •   Dan McCormack    8 年前
    1. 每个功能模块应该在一对名为 feature-name.actions.ts feature-name.state.ts ,位于功能子目录中(请参见 the official style guide )。

    2. 正如您所说,每个特性状态都可以响应在其他状态中定义的操作,并相应地更新自己的状态。下面是一个例子:


    src/app/auth/auth.state.ts(源代码/app/auth/auth.state.ts):

    ...
    // Import our own actions, including the Logout action
    import { Logout, ... } from './auth.actions';
    
    
    export interface AuthStateModel {
      token?: string;
      currentUser?: User;
      permissions: string[];
    }
    
    const defaults: AuthStateModel = {
      token      : null,
      currentUser: null,
      permissions: [],
    };
    
    
    @State<AuthStateModel>({
      name: 'auth',
      defaults
    })
    export class AuthState {
      ...
      // Respond to the Logout action from our own state
      @Action(Logout)
      logout(context: StateContext<AuthStateModel>) {
        context.setState({ ...defaults });
      }
      ...
    }
    

    src/app/users/users.state.ts:

    ...
    // Import our own actions
    import { LoadAllUsers, ... } from './users.actions';
    
    // Import the Logout action from the Auth module
    import { Logout }       from '../auth/auth.actions';
    
    
    export interface UsersStateModel {
      users?: User[];
    }
    
    const defaults: UsersStateModel = {
      users: null,
    };
    
    
    @State<UsersStateModel>({
      name: 'users',
      defaults
    })
    export class UsersState {
      ...
      // An example of the usual case, responding to an action defined in
      // our own feature state
      @Action(LoadAllUsers)
      loadUsers(context: StateContext<UsersStateModel>, action: LoadAllUsers) {
        ...
      }
    
    
      // Respond to the Logout action from the Auth state and reset our state (note
      // that our context is still of type StateContext<UsersStateModel>, like the other
      // actions in this file
      @Action(Logout)
      logout(context: StateContext<UsersStateModel>) {
        context.setState({ ...defaults });
      }
      ...
    }
    

    注意,尽管 AuthState.logout() UsersState.logout() 两者都对 Logout 操作(在AuthState模块中定义),即 authstate.logout()。 函数接受类型的上下文 StateContext<AuthStateModel> ,因为我们要调用上下文的 setState() 函数更新“auth”功能状态。但是, 用户状态。注销() 函数接受类型的上下文 StateContext<UsersStateModel> ,因为我们想打电话 那个 上下文 设置状态() 用于重置“用户”功能状态的函数。

    每个附加的功能模块可以像用户状态一样响应注销操作,并重置自己的状态切片。

        2
  •  1
  •   Rich Duncan    8 年前

    经过一些额外的研究和实验,我可以回答第二个问题——“如何重置所有状态?”我认为行动类只与他们所管理的状态相关联——它们不是。州可以处理您选择的任何操作。所以:

    1. 头组件注入存储服务。
    2. 头的OnLogout发送注销操作。
    3. 通过重置存储的JWT的身份验证状态响应
    4. 任何其他状态都可以响应注销以重置自身
    推荐文章