0

I'm working on an AngularJS service. The first is getting a product's info from an API:

getProductInfo: function(ean) {
    var deferred = $q.defer();

    api.get('products/' + ean, {})
    .then(function(data) {
        service.currentProduct = data;
        deferred.resolve(data);
    }, function() {
        delete service.currentProduct;
        deferred.reject('Invalid EAN: ' + ean);
    });

    return deferred.promise;
},

For the second I want to take the EAN from product's info and use that as the variable to be placed in an external image link:

getProductImg: function() {
    var ean = ???
    var url = "http://externalurl" + ean + "_01c";
    return(url);
},

Ideally I would like to combine these so the external image is part of getProductInfo, is this possible?

Thanks, Shanna

1 Answer 1

2

You can modify your service like that:

angular.module('core.products').service('Products', function($http, $q){    
    this.getInfo = function(ean){
        var defferred = $q.defer();

        $http.get('products/' + ean, {}).then(
            // success
            function(data) {
                var product = data;
                product.img = "http://externalurl" + ean + "_01c";                

                deferred.resolve(product);
            }, 
            // error
            function() {                
                deferred.reject('Invalid EAN: ' + ean);
            }
        );

        return deferred.promise;
    }
})

And use that service in controller:

angular.module('core.products').controller('ProductsController', function($scope, Products){

    $scope.getInfo = function(ean){
        Products.getInfo(ean).then(
            function(product){
                $scope.product = product;
            },
            function(error){
                alert(error);
            }
        )
    }

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

3 Comments

Very good thanks! It's just I need to use service.currentProduct = data; where you have var product = data; Also on your deferred.resolve(product); did you mean to use product over data deferred.resolve(data); ?
If I want to access the image in the controller what would I need to do?
After resolving your promise you can access the image as prop of product. $scope.product.image

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.