首页 > 解决方案 > if 语句基于 3 个不同的条件

问题描述

假设我有一个用户角色列表,并且有 3 个条件将用户重定向到一个页面,并且它基于设置值。

我在下面有我的代码,这是最干净的方法吗?我正在寻求建议。谢谢。

条件是

settings  - if settings has value and user roles not equal to broker -> navigate to properties page
settings  - if settings has no value and user role is equal to broker -> navigate to navigate to transaction page
settings  - if settings has no value and user role not equal to broker -> navigate to index page

#user 角色 ["admin, "broker", "manager" , "consultant"]

#代码

this.userService.updateUserProfileSettings(oldUserProfile)
      .subscribe(
        res =>{            
          const forwardToPage = localStorage.getItem('forwardToPage');
          if(settings && role !== 'Broker'){
           this.route.navigateByUrl('/properties');
          }else if (!settings && role === 'Broker') {
       this.route.navigateByUrl('/transactions');
          }else{
            this.route.navigateByUrl('/index');
          }
        },

标签: javascripttypescript

解决方案


你可以这样做
(但你忘记了 的情况settings has value and user role is equal to broker

const target = ['/index','/properties','/transactions','??index' ] 

function test ( settings,role )
  {
  let condition = (settings ? 1 : 0) + (role === 'Broker' ? 2 : 0)
  console.log (`settings is ${settings} and role is ${role} ==>  ${target[condition]}` )
  }

test( true,  'not Broker' )
test( false, 'Broker'     )
test( false, 'not Broker' )
test( true, 'Broker' )
.as-console-wrapper { max-height: 100% !important; top: 0 }


推荐阅读