0

At the moment, my Angular app looks like this:

Factory in app.js

StoreApp.factory("DataService", function () {

    // create store
    var myStore = new store();

    // create shopping cart
    var myCart = new shoppingCart("Store");

   // return data object with store and cart
   return {
       store: myStore,
       cart: myCart
   };
});

controller.js

    function storeController($scope, $http, $routeParams, $location, DataService) {

            $scope.store = DataService.store;
            $scope.cart = DataService.cart;

            // use routing to pick the selected product
            if ($routeParams.productUrlTitle != null) {
                $scope.product = $scope.store.getProduct($routeParams.productUrlTitle) || $scope.store.getHero($routeParams.productUrlTitle);
            }

            $scope.predicate = '-price';
            $scope.store.isCart = $location.path() == "/cart";
}

In store.js (below) is where my issue is — currently this.products[] takes inline assignments. I need this to instead load an external JSON file (also below). I've tried several things from including/passing the promise to var myStore = new store();, to actually including $http.get() paired with .then() inside of store.js — to no avail.

store.js

function store() {
   this.products = [
       new product("USD", 20, "https://foo.jpg", "Name", "Description"),
   new product("USD", 20, "https://bar.jpg", "Name", "Description"),
];

}
store.prototype.getProduct = function (urlTitle) {
    for (var i = 0; i < this.products.length; i++) {
    if (this.products[i].urlTitle == urlTitle)
        return this.products[i];
    }
    return null;
}

payload.json

[
    {
    "currency": "usd",
    "cost": 1000,
    "image_url": "https://whatever.domain/someimage.jpg",
    "id": "xyz",
    "name": "A title",
    "description": "Some details"
   },
   ...
]

For those interested, my project is based on this: A Shopping Cart Application Built with AngularJS.

Many thanks in advance.


Update

I was able to accomplish what I wanted, but I'm not certain it's the best (Read: correct) way to. In short, I added a new factory called "InventoryService" that I pass to my controller.

app.js

// New Factory Added

StoreApp.factory('InventoryService', ['$http', '$rootScope',
    function ($http, $rootScope) {
        var inventory = [];

        return {
            getInventory: function () {
                return $http.get('http://localhost/ShoppingCart/payload.json').then(function (response) {
                    inventory = response;
                    $rootScope.$broadcast('handleInventoryService', inventory);
                    return inventory;
                })
            }
        };
    }
]);

controller.js

function storeController($scope, $http, $routeParams, $location, InventoryService, DataService) {

    $scope.name = 'inventory';
    (function () {
        InventoryService.getInventory().then(function (inventory) {
            $scope.inventory = inventory;

            for (var i = 0; i < $scope.inventory.data.length; i++) {
                if ($scope.inventory.data[i].id == '11ca3ea26f0e431eb996a401f292581f2') {
                    DataService.store.hero.push(
                        new product(
                            $scope.inventory.data[i].id,
                            $scope.inventory.data[i].image_url,
                            $scope.inventory.data[i].name,
                            $scope.inventory.data[i].description,
                            $scope.inventory.data[i].cost
                        )
                    );
                } else {
                    DataService.store.products.push(
                        new product(
                            $scope.inventory.data[i].id,
                            $scope.inventory.data[i].image_url,
                            $scope.inventory.data[i].name,
                            $scope.inventory.data[i].description,
                            $scope.inventory.data[i].cost
                        )
                    );
                }
            }

            // get store and cart from service
            $scope.store = DataService.store;
            $scope.cart = DataService.cart;
 ...

store.html partial

<div ng-include src="'partials/header.html'"></div>

<div ng-repeat="product in store.hero" class="row-fluid">
    <div class="span12">
        <div class="span4">
            <a href="#/products/{{product.urlTitle}}">
                <img class="img-polaroid" ng-src="{{product.image_url}}" title="{{product.name}}" />
            </a>
        </div>
        <div class="span8">
            <h1 class="tango-tang weight-100">
                {{product.name}}
            </h1>
            <hr />
            <div class="row-fluid">
                <div class="span7">
                    <p>
                        {{product.description}} 
                    </p>
                </div>
                <div class="span5">
                    <div class="well">
                        <h1 class="weight-300 text-center">
                            {{product.price | currency}}
                        </h1>
                    </div>
                    <button class="btn btn-success btn-medium btn-block" ng-click="cart.addItem(product.sku, product.image_url, product.name, product.price, 1)">
                            <i class="icon-plus"></i> Add to Cart 
                    </button> 
                    <a href="#/products/{{product.urlTitle}}" class="btn btn-block">
                        <i class="icon-list"></i> Details
                    </a> 
                </div>
            </div>
        </div>
    </div>
</div>
4
  • 1
    $http and $q should do what you want, you say you tried promise, can you include that piece of code? Commented Jul 10, 2013 at 18:13
  • @jaux - see my updates. Is there a better approach? Commented Jul 10, 2013 at 19:15
  • If the purpose of InventoryService is just to fill up two arrays with initial data, I don't think it's necessary. You may try to make products and hero both promises, later when HTTP responded, resolve two deferred objects at once. Post your HTML where you actually use products and hero, so we can have a better understanding of what your usage is. Commented Jul 10, 2013 at 19:35
  • @jaux - Added the markup for hero which is [nearly] identical to products. Commented Jul 10, 2013 at 20:19

1 Answer 1

1

As I outlined in the comment, the InventoryService isn't necessary in your case, $q and $http.get are enough.

Quoted from comments:

You may try to make products and hero both promises, later when HTTP responded, resolve two deferred objects at once.

Code:

App.factory('DataService', function($http, $q) {
    function Store() {
        var heroDeferred = $q.defer();
        var productsDeferred = $q.defer();

        this.hero = heroDeferred.promise;
        this.products = productsDeferred.promise;

        $http.get('/path/to/payload.json').success(function(data) {
            var hero = [];
            var products = [];

            for (var i = 0, len = data.length; i < len; i++) {
                var prod = data[i];
                if (prod.id === 'xyz') {
                    hero.push(prod);
                } else {
                    products.push(prod);
                }
            }

            heroDeferred.resolve(hero);
            productsDeferred.resolve(products);
        });
    }

    Store.prototype.getProduct = function(urlTitle) {
        return this.products.then(function(products) {
            for (var i = 0; i < products.length; i++) { // MUST use products, it's the real value; this.products is a promise
                if (products[i].urlTitle == urlTitle)
                    return products[i];
            }
            return null;
        });
    };

    ...
    return {
        store: new Store()
        ...
    };
});

http://plnkr.co/edit/qff7HYyJnSdEUngeOWVb

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

3 Comments

This works wonderfully. The only issue that it created is that $scope.store no longer has access to store.prototype.getProduct or store.prototype.getHero which is breaking the routes that allows you drill into the details for each product. See // use routing to pick the selected product in controller.js
@couzzi this.products is now a promise, so store.getProduct should also return a promise. Take a look at "Chaining promises" in the doc, let me know if you still can't figure it out.
I gave it my best shot, and this is as far as I got: $scope.product = $scope.store.hero.then(function(result) { return $scope.store.getHero(result[0].urlTitle); }); No dice.

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.