Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查角色时无限循环。VueJS_Javascript_Typescript_Vue.js_Promise_Jhipster - Fatal编程技术网

Javascript 检查角色时无限循环。VueJS

Javascript 检查角色时无限循环。VueJS,javascript,typescript,vue.js,promise,jhipster,Javascript,Typescript,Vue.js,Promise,Jhipster,有一个导航栏,其中根据用户角色显示元素: <b-navbar-toggle right class="jh-navbar-toggler d-lg-none" href="javascript:void(0);" data-toggle="collapse" target="header-tabs" aria-expanded="false"

有一个导航栏,其中根据用户角色显示元素:

<b-navbar-toggle
    right
    class="jh-navbar-toggler d-lg-none"
    href="javascript:void(0);"
    data-toggle="collapse"
    target="header-tabs"
    aria-expanded="false"
    aria-label="Toggle navigation">
  <font-awesome-icon icon="bars"/>
</b-navbar-toggle>

<b-collapse is-nav id="header-tabs">
  <b-navbar-nav class="ml-auto">
    <b-nav-item-dropdown
        right
        id="pass-menu"
        v-if="hasAnyAuthority('ROLE_USER') && authenticated"
        :class="{'router-link-active': subIsActive('/pass')}"
        active-class="active"
        class="pointer">
                <span slot="button-content" class="navbar-dropdown-menu">
                    <font-awesome-icon icon="ticket-alt"/>
                    <span>First element</span>
                </span>
    </b-nav-item-dropdown>

    <b-nav-item-dropdown
        right
        id="dictionaries-menu"
        v-if="hasAnyAuthority('ROLE_ADMIN') && authenticated"
        :class="{'router-link-active': subIsActive('/dictionary')}"
        active-class="active"
        class="pointer">
                <span slot="button-content" class="navbar-dropdown-menu">
                    <font-awesome-icon icon="book"/>
                    <span>Second element</span>
                </span>
    </b-nav-item-dropdown>
  </b-navbar-nav>
用于使用用户帐户的服务:

export default class AccountService {
  constructor(private store: Store<any>, private router: VueRouter) {
    this.init();
  }

  public init(): void {
    this.retrieveProfiles();
  }

  public retrieveProfiles(): void {
    axios.get('management/info').then(res => {
      if (res.data && res.data.activeProfiles) {
        this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
        this.store.commit('setActiveProfiles', res.data['activeProfiles']);
      }
    });
  }

  public retrieveAccount(): Promise<boolean> {
    return new Promise(resolve => {
      axios
        .get('api/account')
        .then(response => {
          this.store.commit('authenticate');
          const account = response.data;
          if (account) {
            this.store.commit('authenticated', account);
            if (sessionStorage.getItem('requested-url')) {
              this.router.replace(sessionStorage.getItem('requested-url'));
              sessionStorage.removeItem('requested-url');
            }
          } else {
            this.store.commit('logout');
            this.router.push('/');
            sessionStorage.removeItem('requested-url');
          }
          resolve(true);
        })
        .catch(() => {
          this.store.commit('logout');
          resolve(false);
        });
    });
  }

  public hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
    if (typeof authorities === 'string') {
      authorities = [authorities];
    }

    if (!this.authenticated || !this.userAuthorities) {
      const token = localStorage.getItem('jhi-authenticationToken') || sessionStorage.getItem('jhi-authenticationToken');
      if (!this.store.getters.account && !this.store.getters.logon && token) {
        return this.retrieveAccount();
      } else {
        return new Promise(resolve => {
          resolve(false);
        });
      }
    }

    for (let i = 0; i < authorities.length; i++) {
      if (this.userAuthorities.includes(authorities[i])) {
        return new Promise(resolve => {
          resolve(true);
        });
      }
    }

    return new Promise(resolve => {
      resolve(false);
    });
  }

  public get authenticated(): boolean {
    return this.store.getters.authenticated;
  }

  public get userAuthorities(): any {
    return this.store.getters.account.authorities;
  }
}

这是由Vue的反应性引起的。在
v-if
语句中使用async方法,这绝大多数是个坏主意。Vue监视此方法的所有反应依赖项,如果任何依赖项发生更改,它将再次重新计算此语句(这意味着再次调用该函数)。这是故事的一部分

现在,为什么只有角色不同时才会发生这种情况。因为您使用的是共享属性hasAnyAuthorityValue,它是上述方法的被动依赖项

例如:它获取角色用户的权限,立即返回
hasAnyAuthorityValue
(同步),但稍后将在promise(异步)中获取并更新此值。如果异步结果没有改变(一个角色),它可以工作,但当
hasAnyAuthorityValue
的值在角色用户和角色管理员异步结果之间切换时,它会陷入无休止的循环中


有很多解决办法。f、 e.在创建阶段将两个
hasAnyAuthority(any)
的结果保存为数据的属性值,或者为每个角色使用不同的属性名称,而不是共享的属性名称。

谢谢您的回答!我将角色检查分为不同的方法,这真的很有效。我为这个问题添加了一个解决方案。
export default class AccountService {
  constructor(private store: Store<any>, private router: VueRouter) {
    this.init();
  }

  public init(): void {
    this.retrieveProfiles();
  }

  public retrieveProfiles(): void {
    axios.get('management/info').then(res => {
      if (res.data && res.data.activeProfiles) {
        this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
        this.store.commit('setActiveProfiles', res.data['activeProfiles']);
      }
    });
  }

  public retrieveAccount(): Promise<boolean> {
    return new Promise(resolve => {
      axios
        .get('api/account')
        .then(response => {
          this.store.commit('authenticate');
          const account = response.data;
          if (account) {
            this.store.commit('authenticated', account);
            if (sessionStorage.getItem('requested-url')) {
              this.router.replace(sessionStorage.getItem('requested-url'));
              sessionStorage.removeItem('requested-url');
            }
          } else {
            this.store.commit('logout');
            this.router.push('/');
            sessionStorage.removeItem('requested-url');
          }
          resolve(true);
        })
        .catch(() => {
          this.store.commit('logout');
          resolve(false);
        });
    });
  }

  public hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
    if (typeof authorities === 'string') {
      authorities = [authorities];
    }

    if (!this.authenticated || !this.userAuthorities) {
      const token = localStorage.getItem('jhi-authenticationToken') || sessionStorage.getItem('jhi-authenticationToken');
      if (!this.store.getters.account && !this.store.getters.logon && token) {
        return this.retrieveAccount();
      } else {
        return new Promise(resolve => {
          resolve(false);
        });
      }
    }

    for (let i = 0; i < authorities.length; i++) {
      if (this.userAuthorities.includes(authorities[i])) {
        return new Promise(resolve => {
          resolve(true);
        });
      }
    }

    return new Promise(resolve => {
      resolve(false);
    });
  }

  public get authenticated(): boolean {
    return this.store.getters.authenticated;
  }

  public get userAuthorities(): any {
    return this.store.getters.account.authorities;
  }
}
...
  private hasAdminAuthorityValue = false;
  private hasUserAuthorityValue = false;
...
  public hasAdminAuthority(): boolean {
    this.accountService()
      .hasAnyAuthorityAndCheckAuth('ROLE_ADMIN')
      .then(value => {
        this.hasAdminAuthorityValue = value;
      });
    return this.hasAdminAuthorityValue;
  }

  public hasUserAuthority(): boolean {
    this.accountService()
      .hasAnyAuthorityAndCheckAuth('ROLE_USER')
      .then(value => {
        this.hasUserAuthorityValue = value;
      });
    return this.hasUserAuthorityValue;
  }