简体   繁体   中英

Send parameter from controller to service in angularjs

I have the following controller:

class DemandCtrl {
    constructor(ChartDataService) {
        this.ChartDataService = ChartDataService;
        this.dataa = {
            from: 'test1',
            to: 'test2'
        };
    }

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

}


function getData(DemandCtrl) {
    debugger;
    DemandCtrl.ChartDataService.getData().then(result => {
        DemandCtrl.result = result.data;
        getChart(result.data);
    }).catch((e) => {
        console.log(e);
    });
}


  ... other methods/functions...


DemandCtrl.$inject = ['ChartDataService'];

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

I want to get the data from dataa to my service as parameters.

The service looks like this:

export default class ChartDataService {
    constructor($http, authService) {
        this.$http = $http;
        this.authService = authService;
    }
    getData() {
                return this.$http.get(`chartData?&fromDate=` + dataa.from + `&toDate=` + dataa.to)
.then(result => {
            return result;
        }).catch(() => {
            return Promise.reject('Failed to access chart data ');
        });
    }
}

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

What I've tried is to give the dataa as a parameter to getData() but it says it is undefined. Probably I'm not sending them correctly from the controller but I don't know how should I do it.

in the ChartDataService service, just return the http request instead of unwrapping the promise.

export default class ChartDataService {
    constructor($http, authService) {
        this.$http = $http;
        this.authService = authService;
    }
    getData(dataa) {
        return this.$http.get(`chartData?&fromDate=` + dataa.from + `&toDate=` + dataa.to) 
    }
}

Now pass the parameters like this.

DemandCtrl.ChartDataService.getData(this.dataa).then(result => {
        DemandCtrl.result = result.data;
        getChart(result.data);
    }).catch((e) => {
        console.log(e);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM