2016-12-15 30 views
2

我最近一直在看ngrx和redux模式,并在想如何将我现有的Angular2应用程序改写为使用ngrx/store。 我拥有的是一个应用程序,用户可以查看和(如果已登录)可以喜欢并发布引文。 一个典型的引用对象是这样的:Angular2 ngrx的类似Twitter的应用程序。构建AppState

{ text: "Success is the ability to go from one failure to another with no loss of enthusiasm.", publisher: user12345, rank: 14, //some more data }

应用strucure如下所示:

  • 首页 - 要么注册/登录表单或者是随机的引文(如果签署)。
  • 与标签
    • 标签由用户和形式发布的所有引用个人资料页,发布一个新的。
    • 资料信息
  • 引文喂页
  • 页以查看上述其他用户具有相似结构的轮廓。 (当用户点击引用的发布者时)。

所以,我非常沮丧地看到AppState树会如何。

AppState { 
    UserState { 
     UserCitationsState, 
     UserInfoState, 
     AuthState 
    }, 
    RouterState, 
    UserPageState //State representing the other user's page viewed 
    //etc 
} 

主要的问题是 - 我应该存储在每个国家,因为所有的数据是每个请求从后端REST API获取。难道是像e.g只是布尔值:

UserPageState { 
    loading: false, 
    loaded: true 
} 

或应该还可以存储所有信息,并只需更换每次请求一个新的用户页面的时间呢?每当用户导航到其他用户页面时,所有数据都从后端获取。 这就是我的根本困惑 - 如何用redux处理这些类型的应用程序。

编辑 在我限制自己有5个州(5个减速)来表示整个应用程序的那一刻:

  1. AuthState
  2. UserState
  3. UserListState
  4. CitationState
  5. CitationListState

但是,在整体应用程序状态中,我复制了其中的很多应用程序状态。我想这很好。或者会有更好的方法?

export interface AppState 
 
{ 
 
    localUser: AuthState 
 
    
 
    //homePage 
 
    homeCitation: CitationState 
 

 
    //profilePage 
 
    profileInfo: UserState 
 
    profileCitations: CitationListState 
 
    favouriteCitations: CitationListState 
 
    subscribers: UserListState 
 

 
    //userPage (when local user navigates to citation publisher's profile) 
 
    userInfo: UserState 
 
    userCitations: CitationListState 
 
    userSubscribers: UserListState 
 
    
 
    //feedPage 
 
    feed: CitationListState 
 
    
 
    //..... 
 
}

回答

1

我对这个最初的想法去思考应用程序状态的很像你将一个数据库。

我将构建使用以下减速器:然后

AppState: { 
    CitationState 
    UserProfileState, 
    UserInfo, 
    RouterState 
} 

interface CitationState { 
citations: Citation[] 
} 

interface UserProfileState { 
userProfiles: UserProfile[] 
} 

interface UserInfo { 
userInfo: UserInfo 
} 

interface Citation { 
    id: number; 
    publisherId (userId): number; 
    rank: number; 
    text: string; 
} 

interface UserProfile { 
    userId: number; 
    citationIds: number[] 
} 

interface UserInfo { 
    userId: number; 
    authToken: string; 
} 

每个智能组件将构成数据所必需的呈现视图。例如,您可以通过检查路由的用户配置文件是否与UserInfo缩减器中的配置文件相匹配来确定用户配置文件是否属于您自己的配置文件。

不要担心在状态中创建加载/加载,这是您可以从您的商店状态派生出来的东西。由于所有数据都是可观察的,所以当您从中查询数据时,您会获得可用数据的最新快照。

而不是在加载用户引用时绑定到商店的加载属性,而是为该数据构建查询。

例如:

let userCitation$ = state.select(appState => appState.citations) 
    .map(citations => { 
      let userCitation = citations.find(c => c.id === userId); 
      return { 
       loaded: !!userCitation, 
       userCitation: userCitation 
      }; 
    }); 
+0

这是一个很好的答案。比你) –

+0

你可以看看我所做的编辑。你对这种结构有什么看法? Cuz此刻我只能想象我的应用程序状态为每页。 –

+0

这取决于每个州的内容。例如,homeCitation(主页)中包含哪些数据? 对我来说,你似乎应该尝试概括一下数据。这个页面不需要考虑,而是需要将这些数据放在页面缩减器中,而应该考虑如何将这些数据放在其他页面可以使用的地方。 *除非*,你有一个特定的财产,你想保存我wouldnt使redurs到页面。 – cgatian

相关问题