2016-12-15 29 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

相關問題