如何在控制器中提供promise数据对象,并将数据从promise传递给新函数

时间:2015-12-16 07:46:43

标签: javascript angularjs

我已经编写了角度控制器和服务来从json文件中读取数据。服务读取数据并将其传递给控制器​​它工作正常,但当我尝试将此数据分配给新对象时它不会工作。

我想在我的诺言中调用一个新函数,并将我的数据作为对象传递给这个新函数,以便我可以随时使用它。 控制器代码,

class WPEntryController {
    static $inject = ["$location", "WPEntryService"];
    constructor($location, WPEntryService, $http) {
        console.log("IN WPEntryController");
        this.$location = $location;
        this.WPEntryService = WPEntryService;
        this.loadWPEntryPagewithData();

    }
    loadWPEntryPagewithData(){
        this.WPEntryService.loadWPEntryData().then(function(promise){
           this.DataObject = promise;
            this.storeObject();
        });
    }
    storeObject() {
        console.log(this.DataObject);
    }
}
angular.module("app").controller("WPEntryController", WPEntryController);

服务代码,

class WPEntryService {
  static $inject = ["$http"];
  constructor($http) {
    this.$http = $http;
  }
    loadWPEntryData() {
        //read json file or provide URL for data
        var promise = this.$http.get('...')
            .then(function (dataObject) {
                return dataObject.data;
            })
            .catch(function (response) {
                return response;
            });
        return promise;
    }
}

angular.module('app').service('WPEntryService',WPEntryService);

1 个答案:

答案 0 :(得分:0)

你有wrong this context in your then callback。请改用箭头功能:

loadWPEntryPagewithData(){
    this.WPEntryService.loadWPEntryData().then(dataObject => {
//                                             ^^^^^^^^^^^^^^
        this.DataObject = dataObject;
        this.storeObject();
    });
}

但是,这种方法仍然很脆弱,可能无法按预期工作。将promise本身存储在该实例槽中要好得多:

loadWPEntryPagewithData(){
    this.DataPromise = this.WPEntryService.loadWPEntryData();
    this.storeObject();
}
storeObject() {
    this.DataPromise.then(DataObject => console.log(DataObject));
}