简体   繁体   English

如何在服务中进行http调用但得到控制器响应? AngularJS

[英]How to make http call in service but get response by the controller? AngularJS

I`ve got a service where I call http,the problem is that I dont understand how to use $scope.photos in the controller.How to config controller and service to do this? 我有一个叫http的服务,问题是我不了解如何在控制器中使用$ scope.photos。如何配置控制器和服务来做到这一点?

   app.service('http',function($scope,$http){
      function getAll() {
        $http.get('/allphotos').then(function success(response) {
            $scope.photos = response.data;
        }, function error(err) {
            console.log('error is:' + err.err)
        });
    }
});

    app.controller('ctrl',function ($scope, http) {

}

First of all never use $scope inside Service/Factory/Provider. 首先,永远不要在Service / Factory / Provider内部使用$scope The scope is related to controllers only, ae deals with bind views with controllers. 范围仅与控制器有关,ae处理与控制器的绑定视图。


You have a method getAll() that should return Promise and you will be able to resolve it inside your controller. 您有一个应返回Promise的getAll()方法,您将能够在控制器内部对其进行解析。

Something like: 就像是:

app.service('httpService',function(,$http){
      this.getAll = function() {
        return $http.get('/allphotos').then(function(response) {
      //  ^ 'getAll' returns Original Promis comes from '$http'
            return response.data;
      //      ^  here we resolve 'response.data' 
        }, function(err) {
            console.log('error is:' + err.err)
        });
    }
});

And now in controller do: 现在在控制器中执行以下操作:

app.controller('ctrl',function ($scope, httpService) {
   httpService.getAll().then(function(data) {
            $scope.data = data;
        }, function error(err) {
            console.log('error is:' + err.err)
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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