在AngularJS中,如何从服务本身内部的回调中修改服务属性

In AngularJS how to modify service property from callback inside service itself

本文关键字:服务 内部 回调 修改 属性 AngularJS      更新时间:2023-09-26

我有一个工厂,它执行http调用,在错误回调中,我想为属性设置一个值,例如this.password = null,但this.password不指向密码。

另一方面,当我进行POST时,数据被发送得很好:password: this.password

密码属性的范围应该不同,对吗?或者我错过了什么?

.factory('LogInService', function($http) {
  return {
    username: null,
    password: null,
    logIn: function() {
      return $http({
        method: 'POST',
        url: 'http://my-domain/api/signin',
        data: {
          username: this.username,
          password: this.password
        }
      })
      .then(
        function(success){
        },
        function(err){
          // reset password field
          this.password = null;  // <-- not working
        }
      );
    }
  }
});

我可以将所有属性和方法设置为var,然后返回它,但我更喜欢上面的方法。我的意思是:

var myService = {
    // my property and methods...
}
errorCallBack = function(){
  myService.password = null;
}
return myService;

您遇到了范围界定问题。做这样的事情应该很容易。和往常一样,未经测试,但似乎会奏效。

.factory('LogInService', function($http) {
  return {
    username: null,
    password: null,
    logIn: function() {
      var svc = this; //<----
      return $http({
        method: 'POST',
        url: 'http://my-domain/api/signin',
        data: {
          username: svc.username, //<---
          password: svc.password  //<---
        }
      })
      .then(
        function(success){
        },
        function(err){
          // reset password field
          svc.password = null;  //<----
        }
      );
    }
  }
});

您需要了解this

您可以使用箭头函数来解决问题,该函数不会改变this的含义。

您可能希望使用Babel将ES6代码编译为ES5,这样浏览器就可以很好地使用现代代码库。