编辑 - 如果我将 redux-state-sync 配置为使用 localstorage,这一切都有效。我创建了一个包含工作代码示例的存储库https://bitbucket.org/em-aitch/sync-app/src/master/ 。如果广播频道类型(app.component.ts:76)从“localstorage”更改为“native”,则绑定(@select 和 {{ property }} 都不再起作用了!
EDIT2 - 问题如何找出破坏 Angular 绑定的原因?回答这个问题
我已经使用下面描述的 redux-state-sync进行了设置 。redux 状态更改已同步到其他浏览器窗口,但 @select 不起作用。
当我在一个窗口中登录时,app-nav-menu 会出现,因为 ngIf 评估为 true。两个订阅也都写入控制台:
new login state = true app.component.ts:20
subsribed to local observable : true app.component.ts:24
然而,即使在另一个窗口中完成的登录状态更改在那里同步,其他浏览器窗口也不会以相同的方式工作。控制台输出是一样的:
new login state = true app.component.ts:20
subsribed to local observable : true app.component.ts:24
然而,问题是 app-nav-menu 没有出现。下面首先是与此直接相关的代码,最后是 redux 定义。
app.component.html
<body>
<app-nav-menu *ngIf="(isLoggedIn | async)"></app-nav-menu>
<div class="container">
<router-outlet></router-outlet>
</div>
</body>
app.component.ts
export class AppComponent {
title = 'app';
@select((state: IApplicationState) => state.login.isLoggedIn) isLoggedIn: Observable<boolean>;
subscription;
constructor(private ngRedux: NgRedux<IApplicationState>) {
this.subscription = this.ngRedux.select<ILoginState>('login')
.subscribe(newState => {
console.log('new login state = ' + newState.isLoggedIn);
});
this.isLoggedIn.subscribe(newState =>
console.log('subsribed to local observable : ' + newState));
}
}
app.module.ts
import { createStateSyncMiddleware, initStateWithPrevTab } from 'redux-state-sync';
import { Store, createStore, applyMiddleware } from 'redux';
export const store: Store<IApplicationState> = createStore(
rootReducer,
applyMiddleware(createStateSyncMiddleware())
);
export class AppModule {
constructor(ngRedux: NgRedux<any>) {
ngRedux.provideStore(store);
initStateWithPrevTab(store);
}
}
存储/索引.ts
import { combineReducers } from 'redux'
import { ILoginState, loginReducer } from './login'
import { withReduxStateSync } from 'redux-state-sync'
export interface IApplicationState {
login: ILoginState;
}
export const INITIAL_STATE : IApplicationState = {
login : { isLoggedIn: false, tokenInfo : null }
}
const appReducer = combineReducers<IApplicationState>({
login: loginReducer
})
export const rootReducer = withReduxStateSync(appReducer);
就像我在顶部的编辑中所说的那样。如果我将其配置为使用本地存储,则此方法有效:
applyMiddleware(createStateSyncMiddleware(
{ broadcastChannelOption: { type: 'localstorage' } })));