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

how to make available promise data object in controller and pass data from promise to new function

本文关键字:promise 数据 新函数 函数 对象 何使 控制器      更新时间:2023-09-26

我已经编写了角度控制器和服务来从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);

您的then回调中有错误的this上下文。使用箭头功能:

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));
}