2016-07-10 2 views
0

을 거치지 않고 API를 GET 전화를 사용할 수 내 service.js입니다 웹 API를 사용하는 방법은 '$ 범위'를 서비스의 기능에 전달하지 않고 얻을 수 있습니까? 이 같은 예를 들어 (나는 이것을 시도했지만 작동하지) :

... 
this.getSomething = function(){ 
    return $http({ 
     ... 
    }).success(function(response){ 
     return response; 
    }).error ... 
     ... 
} 

를 다음 컨트롤러 :

... 
$scope.items = myService.getSomething(); 
+0

'성공'기능 대신 '다음'을 사용하는 것이 좋습니다. http://blog.ninja-squad.com/2015/05/28/angularjs-promises/ 및 https://www.peterbe.com/plog/promises-with-$http를 참조하십시오. –

답변

0

예, 당신이 컨트롤러에있는없이 $http 서비스를 사용할 수 있습니다.
서비스 나 공장에 http 호출을 넣을 수 있습니다.

app.service('MyHttpService', function($http) { 
    this.getData = function(id) { 
    $http.get(<URL>, <PARAMS>).then(function(success) { 
     return success; 
    }, function(err) { 
     return err; 
    }); 
    } 
}); 

// In you Controller 

app.controller('MyCtrl', function(MyHttpService){ 
    $scope.data = getData .getData(); 
}) 

이 당신이 약속과 직접적으로 데이터를 반환하여이 MyHttpService 더 강력한 만들 수있는 단순한 예입니다;

0

예, 앞으로 나아가려면 일반적으로 $ scope를 사용하지 않는 것이 가장 좋지만 서비스에 전달할 필요가 없습니다. 이것은 일반적으로 내 서비스/컨트롤러를 어떻게 모델링하는지입니다.

서비스 :

//Using es6 syntax 
this.getData() { 
    return $http.get('/api/') 
     .then(({data}) => data) 
     .catch(({data}) => console.log('FAILED: ', data.message)); 
} 

//es5 
this.getData() { 
    return $http.get('/api/') 
     .then(function(res) { 
      return res.data 
     }) 
     .catch(function(res) { 
      console.log('FAILED: ', res.data.message)); 
     }); 
} 

컨트롤러 :

//es6 
apiService.getData() 
    .then(data => this.data = data); 

//es5 
apiService.getData() 
    .then(function(data){ 
    this.data = data; 
    }); 
0

당신은 서비스에 $ 범위를 통과 할 수 없습니다. $ scope는 컨트롤러에서 뷰에 바인딩하는 데 사용됩니다.

app.controller('myCtrl', function($scope, service) { 

    $scope.items = service.getItems(); 

}); 

app.service('service', function() { 

    this.getItems() { 
    return $http.get('/api/items') 
    .then(function(res) { 
     return res.data 
    }) 
    .catch(function(res) { 
     ... 
    }); 
    } 

});