0

After a few tries, I am now able to access the external service factory (was told it's a good practise to decentralise it) to retrieve product data and display them in my view.

At the moment I am passing the $scope to the function, which seems kind of ugly (especially if you add further CRUD methods).

Is there a better / more appropriate way to achieve this?

Thanks in advance.

At the moment I use it as seen below (which is working):

services.js

angular.module('services', [])
.constant("baseDataUrl", "http://localhost:55451/api/")
.factory('sportsstoreService', function ($http, baseDataUrl) {

    var serviceApi = {};

    serviceApi.getProducts = function ($scope) {
         $http({ method: 'GET', url: baseDataUrl + 'product' }).
         success(function (data, status, headers, config) {
              $scope.data.products = data;
         }).
         error(function (data, status, headers, config) {
             // called asynchronously if an error occurs
             // or server returns response with an error status.
         });
    };

    return serviceApi;        
});

sportsstore.js

angular.module("sportsStore")
    .controller("sportsStoreCtrl", function ($scope, sportsstoreService) {

        $scope.data = {};

        sportsstoreService.getProducts($scope);

});
1
  • 1
    Take a look at angular $resource service (docs.angularjs.org/api/ngResource/service/$resource). You could return in your sportService factory the new instance of object returned by $resource and then use it like SportService.get(); Commented Aug 14, 2014 at 10:00

2 Answers 2

2

Change your service so that the function returns a promise, like so:

serviceApi.getProducts = function () {
  return $http
    .get(baseDataUrl + 'product')
    .then(
      function success (response) {
        return response.data;
      },
      function error (reason) {
        // Do something!
      }
    );
};

and then in your controller:

$scope.data = sportsstoreService.getProducts();

For info on promises:

https://egghead.io/lessons/angularjs-promises

https://egghead.io/lessons/angularjs-chained-promises

https://docs.angularjs.org/api/ng/service/$q

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

Comments

1

You can create an factory which will return angular's $resource object. Angular $resource object has default actions:

 { 'get':    {method:'GET'},
    'save':   {method:'POST'},
    'query':  {method:'GET', isArray:true},
    'remove': {method:'DELETE'},
    'delete': {method:'DELETE'} };

but you can extend them with your own custom actions. Read more here: https://docs.angularjs.org/api/ngResource/service/%24resource

There is an example:

.factory('SportsStoreService', function ($http, baseDataUrl) {
    var serviceApiCustomMethods={};

    serviceApiCustomMethods.getSimillarItems ={
        method: 'GET',
        url: baseDataUrl + 'product/simillar/:id',
        isArray: true
    };

    return $resource(baseDataUrl + 'product/:id',{}, serviceApiCustomMethods);

});

And usage:

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

    SportsStoreService.query(function(response){
        //success
    },function(response){
        //error
    });

    SportsStoreService.get({id:'123'},function(response){
        //success
    },function(response){
        //error
    });

    SportsStoreService.getSimillarItems({id:'456',additionalGetParam: 5, anotherParam: desc},function(response){
      //success
    }); /*url's :id will be replacad with given id value because it matches url param in method declaration. 
       Rest of params will be added as GET params - ?additionalGetParam=5&anotherParam=desc*/       
});

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.