为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

in_house 2016-01-30 11:50:39
查看完整描述

2 回答

已采纳
?
紫帆梓

TA贡献3条经验 获得超3个赞

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


查看完整回答
2 反对 回复 2016-02-02
?
李晓健

TA贡献1036条经验 获得超461个赞

在service 中写一个发送请求的方法,然后把这个service注入到 controller中,然后直接调用service的方法就行了

查看完整回答
反对 回复 2016-01-30
  • 2 回答
  • 0 关注
  • 3495 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信