moh_abk
moh_abk

Reputation: 2164

AngularJS service with data from REST API

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?

Upvotes: 0

Views: 1568

Answers (2)

Brooklyn Nicholson
Brooklyn Nicholson

Reputation: 646

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.

Upvotes: 0

Behrooz
Behrooz

Reputation: 1965

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.

Upvotes: 1

Related Questions