代码之家  ›  专栏  ›  技术社区  ›  Charles Watson Darin Dimitrov

类函数返回promise$$state对象而不是普通对象?

  •  2
  • Charles Watson Darin Dimitrov  · 技术社区  · 10 年前

    这个问题与之前存在的问题类似,但由于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;
    

    返回:

    enter image description here

    低于$$state级别的任何内容都不可访问。 $$state.value 返回未定义的。

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

    2 回复  |  直到 10 年前
        1
  •  1
  •   Jorawar Singh    10 年前

    这是一个你需要解决的承诺。您正在从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;
        });
      }
    
        2
  •  0
  •   Charles Watson Darin Dimitrov    10 年前

    解决方案!

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

    enter image description here