首页 > 解决方案 > 如何找出破坏 Angular 绑定的原因?

问题描述

我有支持多个浏览器选项卡的角度应用程序,这些选项卡有 2 个绑定,其他使用 angular-redux @select 和其他一个 {{ property }}。该应用程序按预期工作。但是,我可以通过使用 redux-state-sync 中间件配置我的 Angular 存储以使用广播通道而不是本地存储来打破绑定。因此,在 app.component.ts 中用其下方的注释行替换一行会破坏第二个浏览器窗口中的绑定。这看起来真的很奇怪,我不知道如何找出为什么两个绑定都从看似不相关的变化中中断。

编辑:参考 yurzui 的回答:状态在选项卡之间同步也与广播频道选项。只有绑定不再起作用。这可以在按下按钮时在不同浏览器选项卡的控制台输出中验证。

app.component.html

<div style="text-align:center">
  <div *ngIf="(isLoggedIn | async)">
    <p>this appears when logged in!</p>
  </div>
  <h1>
    App status is {{ statusTxt }}!
  </h1>
  <button (click)="toggleLogin()">{{ buttonTxt }}</button>
  <h2>You can either login 1st and then open another tab or you can 1st open another tab and then login. Either way the both tabs should be logged in and look the same</h2>
  <h2>After testing multiple tabs with current 'localstorage' broadcastChannelOption type, you can change it to 'native' in app.component.ts and you'll see that bindings do not work anymore</h2>
</div>

app.component.ts

import { Component, Injectable } from '@angular/core';
import { createStateSyncMiddleware, initStateWithPrevTab, withReduxStateSync } from 'redux-state-sync';
import { combineReducers, Action, createStore, applyMiddleware } from 'redux';
import { NgRedux, select } from '@angular-redux/store';
import { Observable } from "rxjs";

export interface LoginToggle {
  isLoggedIn : boolean
}

export interface LoginToggleAction extends Action {
  loginToggle: LoginToggle;
}

@Injectable()
export class LoginActions {
  static TOGGLE_LOGIN = 'TOGGLE_LOGIN';

  toggleLogin(loginToggle: LoginToggle): LoginToggleAction {
    return { 
        type: LoginActions.TOGGLE_LOGIN, 
        loginToggle 
    };
  }
}

export interface ILoginState {
  readonly isLoggedIn: boolean;
}

export interface IApplicationState {
  login: ILoginState;
}

export const INITIAL_STATE : IApplicationState = {
   login : { isLoggedIn: false } 
}

export function loginReducer(oldState: ILoginState = { isLoggedIn : false } as any, action: Action) : ILoginState {
  switch (action.type) {
      case LoginActions.TOGGLE_LOGIN: {
          console.log('in reducer');
          const toggleAction = action as LoginToggleAction;
          return {
              ...oldState,
              isLoggedIn: toggleAction.loginToggle.isLoggedIn
          } as ILoginState;       
      }
      default: {
        return oldState;
    }
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  statusTxt = 'logged out';
  subscription;
  loginStatus = false;
  buttonTxt = 'Login';

  @select((state: IApplicationState) => state.login.isLoggedIn) isLoggedIn: Observable<boolean>;

  constructor(private ngRedux: NgRedux<IApplicationState>, 
    private actions : LoginActions) {

    const appReducer = combineReducers<IApplicationState>({
      login: loginReducer
    })

    const rootReducer = withReduxStateSync(appReducer);
    const store = createStore(rootReducer,
      applyMiddleware(createStateSyncMiddleware({ broadcastChannelOption: { type: 'localstorage' } })));

    /* !! Both bindings break if i replace the row above with this: 
    applyMiddleware(createStateSyncMiddleware())); */

    initStateWithPrevTab(store);

    ngRedux.provideStore(store);

    this.subscription = this.ngRedux.select<ILoginState>('login')
      .subscribe(newState => {
        console.log('new login state = ' + newState.isLoggedIn);
        this.loginStatus = newState.isLoggedIn;
        if (newState.isLoggedIn) {
          this.statusTxt = 'logged in!';
          this.buttonTxt = 'Logout';
        }
        else { 
          this.statusTxt = 'logged out!';
          this.buttonTxt = 'Login';
        }
        console.log('statusTxt = ' + this.statusTxt);
    });
  }

  toggleLogin(): void {
    this.ngRedux.dispatch(this.actions.toggleLogin({ isLoggedIn: !this.loginStatus }));
  }
}

标签: angular

解决方案


当您使用本地存储通道时,您的应用程序将订阅浏览器存储事件。并且一旦您的应用程序更改了一个选项卡中的值,它就会更新 locastorage 触发storage另一个选项卡中的事件,因此它会更新。

使用默认redux_state_sync频道,您在选项卡之间没有这种连接,但频道现在使用未由 zonejs 修补的 BroadcastChannel 因此您始终会收到不在角度区域中的消息。

你能做什么?

订阅时在 Angular 区域内手动运行代码:

constructor(...private zone: NgZone) {

this.subscription = this.ngRedux.select<ILoginState>('login')
  .subscribe(newState => {
    this.zone.run(() => {  // enforce the code to be executed inside Angular zone
      console.log('new login state = ' + newState.isLoggedIn);
      this.loginStatus = newState.isLoggedIn;
      ...
    })
});

请注意,您也可以运行 cdRef.detectChanges,但在这种情况下,您可能会遇到一些 Angular 处理程序将在 Angular zone 之外注册的情况因此,您将在其他地方调用 detectChanges 或再次使用 zone.run

所以我建议你使用 zone.run 来确保你在 Angular 应用程序中的正确区域


推荐阅读