0

I'm starting to read about services in Angular and confused as to how to use them with $http.

I currently use $http to fetch data from my REST API like the code below;

$scope.getRestaurant = function () {
    var baseUrl = 'http://api.example.com/web/restaurant/details/' + $scope.id;
    $http({
        method: 'get',
        url: baseUrl,
        headers: {'Content-Type': 'application/json'}
    }).
    success (function(data, status, headers, config){
        if(data && !angular.isUndefined(data) ){
            $scope.restaurant = data;
        } else {
            $scope.restaurant = [];
        }
    }).
    error(function(data, status, headers, config) {
        //$scope.messageFailure(data.message);
    });
}

$scope.id is a value on my controller how can I turn this function into service and then access the data returned in my controller?

2
  • Do you want this in a service because you intend to pass it around to multiple controllers? Commented Feb 2, 2016 at 18:00
  • Yes correct, that's why Commented Feb 2, 2016 at 18:03

2 Answers 2

1

This is how you can create a factory or service that has a function which takes an argument, you can then pass $scope.id in your controller to that function. So to start, create a factory:

app.factory('myFactory', function($http) {

    var factory = {};

    var _myfunction = function(id)
    {
        return $http.get('http://api.example.com/web/restaurant/details/'+id);
    }

    factory.myFunction = _myfunction;

    return factory;
});

and then in your controller, you will have:

app.controller('myCtrl', function('myFactory'){
    var x = $scope.id;

    $scope.getRestaurant = function (x) {
        myFactory.myFunction(x).success(function(data, status, headers, config){
            //whatever...
        }).error(function(){
            // whatever....
        })
    };
});

Of course it's just a general idea, you need to tweak it to meet your exact needs.

Sign up to request clarification or add additional context in comments.

2 Comments

isn't .error() and .success() deprecated?. i think he should use .then() instead.
Well which version of angular are you using? I think I am using the latest one (not the version 2 though) and it still has them. Maybe I should look again ;) But I think he gets the point.
0

You have to inject the service into the controller and talk to it through there.

Quick example:

Your service

app.service '$restaurants', ['$http', '$q', ($http, $q) ->
    fetch: (id) ->
        deferred = $q.defer()
        config =
            url: "//api.example.com/web/restaurant/details/#{id}"
            method: 'GET'
            headers: 'Content-Type': 'application/json'
            dataType: 'json'

        x = $http config
        x.error (data, status) -> deferred reject data, status
        x.success (response, status, headers, config) ->
            deferred.resolve response

        deferred.promise

Controller injects the service

app.controller 'GodClass', ['$restaurants', ($restaurants) ->
    $scope.id = 1

    $restaurants.fetch($scope.id).then (response) ->
        console.log response

Very much simplified but it'll get you the results based on the ID that you pass to the service.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.