【问题标题】:Class function returns promise $$state object instead of plain object?类函数返回promise $$state 对象而不是普通对象?
【发布时间】:2016-08-04 18:11:50
【问题描述】:

这个问题有类似的预先存在的问题,但由于 ES6 类的性质,我认为它们并不相同。

我有一个返回对象的服务,但它以承诺状态对象而不是普通对象的形式返回它,因此无法访问数据。

下面我展示了我如何调用函数,并从 promise 和函数返回,但是返回函数返回 $q promise 而不是内部返回的数据。

class EnterpriseController {
  /*@ngInject*/
  constructor(EnterpriseService, $scope) {
    this.name = 'enterprise';
    this.systemId = 20003
    this.pageLink = '#/enterprise';
    this.$scope = $scope;
    this.EnterpriseService = EnterpriseService;
    this.$scope.data = this.getEnterpriseData();
  }

  getEnterpriseData() {
    this.EnterpriseService.getData().then(function(response) {
      return response.data;
    });
  }
}

EnterpriseController.$inject = ["EnterpriseService", "$scope"];
export default EnterpriseController;

返回:

$$state 级别以下的任何内容均不可访问。 $$state.value 返回未定义。

最终,我想访问构造函数中返回的数据,但我只能访问似乎是 $q 承诺的内容。

【问题讨论】:

  • 这是一个你需要解决的承诺。
  • @CharlesWaston 我认为现在已经修复了吗??
  • 它仍然未定义。
  • 但在您从 this.scope.data 获得 $$state 对象之前?

标签: angularjs ecmascript-6 angular-promise


【解决方案1】:

这是一个你需要解决的承诺。您正在从 getEnterpriseData() 方法返回一个承诺

来自

constructor(EnterpriseService, $scope) {
    this.name = 'enterprise';
    this.systemId = 20003
    this.pageLink = '#/enterprise';
    this.$scope = $scope;
    this.EnterpriseService = EnterpriseService;
    this.$scope.data = this.getEnterpriseData();
  }

  getEnterpriseData() {
   return this.EnterpriseService.getData().then(function(response) {
      return response.data;
    });
  }

  constructor(EnterpriseService, $scope) {
    this.name = 'enterprise';
    this.systemId = 20003
    this.pageLink = '#/enterprise';
    this.$scope = $scope;
    this.EnterpriseService = EnterpriseService;
     this.getEnterpriseData().then(function(data){
      this.$scope.data = data;
      console.log(this.$scope.data)
     });
  }

  getEnterpriseData() {
   return this.EnterpriseService.getData().then(function(response) {
      return response.data;
    });
  }

【讨论】:

  • 那么究竟要做什么? getEnterpriseData() { this.EnterpriseService.getData().then(function(response) { return response.data; }); }
  • 试试 this.getEnterpriseData().then(function(data){ this.$scope.data = data; console.log(this.$scope.data) });
  • 是的,如果您返回已解析的数据也应该可以使用
  • 这些都不起作用。第一个选项不正确,因为“this.getEnterpriseData()”在错误的上下文中使用了“this”,如官方 MDN 页面中所述:(developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)。第二个选项简单地返回“未定义”
  • 据我所知,ES6 类中的“this”没有引用正确的上下文。
【解决方案2】:

解决方案!

我只需要在初始类上下文中捕获 $scope,所以第 13 行解决了这个问题:

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 2021-08-04
    • 2021-05-18
    • 2020-11-28
    • 1970-01-01
    • 2020-03-14
    • 2018-11-03
    • 2016-08-31
    相关资源
    最近更新 更多