【问题标题】:Changes to a property in a service not triggering a change对服务中属性的更改不会触发更改
【发布时间】:2017-09-14 22:43:33
【问题描述】:

我有以下UserService,我只是在实例中拥有一个属性,用于确定用户是否isAuthenticated。出于某种原因,即使通过将this.isAuthenticated 设置为不同的值来更改值,在logout 和其他一些方法上,Angular 也不会捕获该更改。我什至尝试过手动编写$digest$apply,但仍然没有运气。

export default class UserService {

  constructor($http, $state, AppConstants, JWTService) {
    'ngInject';

    this.$http = $http;
    this.$state = $state;

    this.isAuthenticated = false;
  }


  logout() {
    this.isAuthenticated = false;
    this.$state.go('login', null, { reload: true });
  }

  verify() {
    return new Promise((resolve) => {

      // if a user exists, then resolve
      if (this.isAuthenticated) {
        return resolve(true);
      }

      this.$http({
        method: 'POST',
        url: `${this.AppConstants.api}/verify`
      })
      .then(() => {
        this.isAuthenticated = true;
        return resolve(true);
      })
      .catch(() => {
        this.isAuthenticated = false;
        return resolve(false);
      });
    });
  }

}

代码有效,当我第一次登录时,我将 this.isAuthenticated 设置为 true,this.verify 通过发布来工作。但是,当我logout 时,即使this.isAuthenticatdfalse 如此,当再次调用this.verify 时,条件if (this.isAuthenticated) 仍然是true

【问题讨论】:

  • 这似乎是一个 Angular v1 问题?如果是这样,请更新您的标签。 angular 用于 Angular v2+,angularjs 用于 Angular 1。谢谢!
  • 更新了标签。

标签: angular-services angularjs


【解决方案1】:

"this" 不是您认为的 .then() 函数中的内容。范围发生了变化。这种情况很常见,在使用 javascript 时您必须始终牢记这一点。以下是您可以采取的措施的一个示例:

javascript promises and "this"

【讨论】:

  • 我知道this 是什么,因为上下文保持不变,因为我们使用的是粗箭头语法。我已经对此进行了测试,以确保我们处于相同的上下文中。
猜你喜欢
  • 2021-09-18
  • 2021-01-21
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 2012-09-04
相关资源
最近更新 更多