将方法从服务调用到控制器

时间:2017-10-24 12:57:19

标签: javascript angularjs

我有这种服务结构:

export default class ChartDataService {
    constructor($http, authService) {
        this.$http = $http;
        this.authService = authService;
    }
     getData(dataa) {       

      //do something

}

ChartDataService.$inject = ['$http', 'authService'];

控制器结构:

class DemandCtrl {
    constructor(ChartDataService) {
        this.ChartDataService = ChartDataService;
        this.dataa = {
            from: '10/01/2017',
            to:  '10/03/2017'
        };
    }

    $onInit() {
        getData.call(null, this);       
    }

    update() {
        console.log('show something');
        DemandCtrl.ChartDataService.getData(this.dataa);        
    }
}
...
DemandCtrl.$inject = ['ChartDataService'];

export const Demand = {
    bindings: {
        data: '<'
    },
    templateUrl: demandPageHtml,
    controller: DemandCtrl
};

我想从服务中调用update() getData()函数。无论我如何尝试getData()ChartDataService.getData(this.dataa)DemandCtrl.ChartDataService.getData(this.dataa),我都会遇到同样的错误:未定义。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

答案是使用.call()中的$onInit()

在这种特殊情况下,update()的内容必须是:

update() {
        getData.call(null, this);       
    }
相关问题