AngularJS 在controller中如何从service获取异步请求数据?

in_house
浏览 3498回答 2
2回答

紫帆梓

使用promise模式:service代码app.service('IndexServ',function($http,$q){     this.getData = function(){ //暴露一个接口         //获取数据,并缓存数据         return $http.get('data/data.json',{cache:true}).then(function (d) {             this.data = d;             return $q.when(d);         }, function (d) {             return $q.reject(d);         });     }; });controller代码app.controller('IndexCtrl',function($scope,IndexServ){     IndexServ.getData().then(function(res){ //调用获取数据的接口         $scope.data = res.data;     }); }

李晓健

在service 中写一个发送请求的方法,然后把这个service注入到 controller中,然后直接调用service的方法就行了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS