2017-07-31 118 views
1

我正在从Angular 2升级到Angular 4 + Universal。在以前的版本中,我在reducer中使用存储状态来设置初始状态。 getInitialState函数将设置状态,然后检查缓存是否有以前的值并更新状态。状态然后在导出的默认功能user中返回。如何在Angular Universal应用程序中设置初始状态?

function getInitialState() { 
let initialState; 
const emptyState = { 
    categories: null, 
    seeAllUsers: null, 
    groups: userGroupExists(), 
    formData: null, 
    bonusSeeAllUsers: null, 
    fetching: false, 
    searchResults: null 
}; 
if (isBrowser) { // here is my problem 
    if (window['UNIVERSAL_CACHE'] !== undefined) { 
     const cache = JSON.parse(window['UNIVERSAL_CACHE'].CacheService); 
     if (cache) { 
      initialState = { 
       groups: cache.groups ? updateGroups(cache.groups) : null, 
       seeAllUsers: cache.seeAllUsers ? updateSeeAllUsers(cache.seeAllUsers) : null, 
       groups: userGroupExists(), 
       formData: null, 
       bonusSeeAllUsers: null, 
       fetching: false, 
       searchResults: null 
      }; 
     } else { 
      initialState = emptyState; 
     } 
    } else { 
     initialState = emptyState; 
    } 
} else { 
    initialState = emptyState; 
} 
return initialState; 
} 

export default function user(state: any = initialState, action: Action{ 
     switch (action.type) { 
     case TYPES.RECEIVE_USERS_SEE_ALL_BEGIN: 
      let nextSeeAllBeginState; 
      if (action.payload.data === 0) { 
      return assign({}, state, { 
      seeAllUsers: {}, 
      bonusSeeAllUsers: {}, 
      fetching: true 
      }); 
      } 
     }  
    } 

由于最近更新角环球,其对PLATFORM_ID注入构造函数来检查代码在浏览器或服务器这样的运行要求:

constructor(@Inject(PLATFORM_ID)platformId: string){ 
    isPlatformBrowser(platformId){ 
     // access window 
    }; 
} 

由于减速器不能使用任何角装饰器,如何利用缓存中的值来更新我的状态?

回答

0

您是否尝试过/抓住窗口?例如:

try { 
    const cache = window.UNIVERSAL_CACHE; 
} catch (e) {} 

这就是我在导入platformId之前如何管理浏览器特定的代码以实现通用兼容。

+0

感谢您的支持。有必要使用'try'和'catch'来查看缓存是否可用。我会尝试一下,让它知道它是否有效。 –

相关问题