javascript - Angular Service working synchronously with Controller -


i'm new angularjs , have begun grasp many of concepts mvc design pattern. having difficult time implementing service layer in application.

what finding after controller calls method within service, continues code execution before service returns data; time service return data, isn't of use controller.

to give better example of i'm saying, here code:

var insightapp = angular.module('insightapp', ['chart.js']);  // module declaration factory containing service insightapp.factory("dataservice", function ($http) { return {     getchartselections: function () {             return $http.get('home/getsalesdata')                 .then(function (result) {                 return result.data;             });         }     }; });  insightapp.controller("chartselectioncontroller", getavailablecharts);  // 2nd controller calls service insightapp.controller("datacontroller", function($scope, $http, dataservice){ var response = dataservice.getchartselections();  // method executed before service returns data  function workwithdata(response){     // data    } } 

all examples i've found seem constructed have here or slight variation; not should doing ensure asynchronous execution.

in javascript world, i'd move service inside of controller make executes async; don't how make happen in angular. also, counter intuitive against angular injection anyway.

so proper way this?

http return promise not data, in factory returning $http promise , can use promise then, catch, method.

see: http://blog.ninja-squad.com/2015/05/28/angularjs-promises/

insightapp.controller("datacontroller", function($scope, $http, dataservice){  var response = dataservice.getchartselections()     .then(function(res) {        // execute when have data     })     .catch(function(err) {       // execute if have error in http call     }); 

edit pass params model service:

insightapp.factory("dataservice", function ($http) { return {     getchartselections: function (yourparameter) {             console.log(yourparameter);             return $http.get('home/getsalesdata')                 .then(function (result) {                 return result.data;             });         }     }; }); 

and :

insightapp.controller("datacontroller", function($scope, $http, dataservice){  var response = dataservice.getchartselections('only pie one')     .then(function(res) {        // execute when have data     })     .catch(function(err) {       // execute if have error in http call     }); 

Comments