Angular 如何在角度通用应用程序中设置初始状态?

Angular 如何在角度通用应用程序中设置初始状态?,angular,window,server-side-rendering,angular-universal,Angular,Window,Server Side Rendering,Angular Universal,我正在从Angular 2升级到Angular 4+Universal。在以前的版本中,我使用reducer中的存储状态来设置初始状态。getInitialState函数将设置状态,然后检查缓存中以前的值并更新状态。然后在导出的默认函数user中返回状态 function getInitialState() { let initialState; const emptyState = { categories: null, seeAllUsers: null, group

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

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
           });
          }
        }    
    }
由于Angular Universal最近进行了更新,因此需要将
平台ID
注入构造函数,以检查代码是否在浏览器或服务器上运行,如下所示:

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

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

是否尝试了try/catch around窗口?例如:

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

在引入platformId之前,我就是这样管理特定于浏览器的代码以实现通用兼容性的。

您是否尝试过try/catch-around窗口?例如:

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

在引入platformId之前,我就是这样管理特定于浏览器的代码以实现通用兼容性的。

谢谢。使用
try
catch
查看缓存是否可用是有意义的。我会试试看,然后告诉你是否有效。谢谢你。使用
try
catch
查看缓存是否可用是有意义的。我会试试看,如果行得通就告诉你。