【问题标题】:Negating the result of a promise in a guard在守卫中否定承诺的结果
【发布时间】:2017-08-31 18:28:05
【问题描述】:

我有一个带有canActivate() 的工作angular2 守卫,它调用isLoggedIn() 的服务并返回一个承诺,然后解决并适当地处理路线。

但是,我正在尝试做相反的事情,看看用户何时没有登录,并且它不工作。

我尝试了这么简单的方法(添加一个 ! 运算符),希望它能起作用:

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService) {}

    canActivate() {
        return !this.authService.isLoggedIn();
    }
}

但是,这总是返回一个错误的值,并且路由永远不会激活。

这是我的isLoggedIn() 函数的相关摘录:

isLoggedIn(): Promise<Boolean> {
  var component = this;
  return new Promise((resolve, reject) => {       
      component.queryForUser((user) => {
        resolve(user != null);
      });
    }
  });
}

如果用户不等于null,那么他已经登录并且promise 解析为true。否则,假的。

虽然我可以简单地添加一个参数来指定我正在寻找的状态,甚至可以创建一个isNotLoggedIn() 函数,但逻辑相同但相反,我问,有没有办法否定承诺的解析值对于canActivate()

【问题讨论】:

  • 像对待承诺一样对待承诺。 .then(...)

标签: angular typescript promise angular2-routing


【解决方案1】:

如果您在 if 语句中并且启用了 async/await,则将否定句移到括号内。

if (!await client.bucketExists('test')) {}

【讨论】:

    【解决方案2】:

    return !this.authService.isLoggedIn() 不起作用,因为 JS 是如何工作的。 this.authService.isLoggedIn() 是承诺对象并且是真实的。 !this.authService.isLoggedIn() 永远是假的。

    相反,promise 结果应该被映射到否定结果

    canActivate() {
        return this.authService.isLoggedIn().then(result => !result);
    }
    

    或者

    async canActivate() {
        return !(await this.authService.isLoggedIn());
    }
    

    await ... 周围的括号是可选的,用于提高可读性。

    【讨论】:

    • 我是 TypeScript 的新手。到目前为止,我使用(a) =&gt; (sth(a)) 中的=&gt; 运算符作为function(a) { sth(a) } 的简写。在这种情况下,=&gt; 在做什么?是一样的吗,只是更短?
    • 严格来说是function(a) { return sth(a) },要时刻牢记隐式返回,因为它会毁了事情。是的,它是一个参数的简写。使用或不使用它是一个品味问题。我个人不会在我自己的风格指南中使用它,因为它不一致(这里特别讨论了不一致之处 stackoverflow.com/a/41086381/3731501)。
    【解决方案3】:

    您需要做的就是进一步操作 promise 的解析值:

    canActivate() {
        return this.authService.isLoggedIn().then(loggedIn => !loggedIn);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-04
      • 2017-10-18
      • 2016-09-17
      • 1970-01-01
      • 2019-01-05
      • 2017-08-04
      • 2019-07-09
      • 1970-01-01
      相关资源
      最近更新 更多