Jose the hose
Jose the hose

Reputation: 1895

Issue displaying JSON through a service with Angular

I have created a service which reads json and returns data. But for some reason it does not seem to work and is not giving me an error - which is making it really hard to debug. I was hoping someone here might find the issue.

First up, I have this controller in a file called build-controler.js

'use strict';
(function () {

var app = angular.module('priceQuoteApp');

var quoteBuilderController = function ($scope, $http, $timeout, ProductsFactory) {

    var products = ProductsFactory.loadProducts();

    $scope.listOfProducts = products;

//other stuff going on 
};

app.controller('quoteBuilderController', ['$scope', '$http', '$timeout', 'ProductsFactory', quoteBuilderController]);

}());

The loadProducts() function is sitting in my service called service-js and looks like this...

'use strict';
var priceQuoteApp = angular.module('priceQuoteApp');

var loadProductUrl = "scripts/json/sample-products.json";

priceQuoteApp.factory("ProductsFactory", function ($http) {

return {
    loadProducts: function () {
        //Create an object to hold your result
        var result = {};

        $http.get(loadProductUrl)
            .then(function (allProducts) {
                result = allProducts.data.Connectivity;
            })
            .finally(function () {

            });
    }
};
});

The reason 'Connectivity' is added to data is because I only want to select that part of nested json

{
"Connectivity": [
    {"product_id": 1, "product_name": "bla" },
    {"product_id": 2, "product_name": "bla2"}
],
"Other": [
    {"product_id": 1, "product_name": "bla" },
    {"product_id": 2, "product_name": "bla2"}
]

}

Finally in my view I am trying to display the result in a ng-repeat but its not working

<table class="table table-hover margin bottom table-striped">
                <tr ng-repeat='product in listOfProducts'                        >
                 <td><h4>{{product.product_name}}</h4></td>
                </tr>
</table>

Can anyone see what I am doing wrong? Am I injecting ProductsFactory correctly? Thanks

Upvotes: 0

Views: 42

Answers (1)

mindparse
mindparse

Reputation: 7225

I think its just a case that you need to actually return the result of your $http call.

You are assigning the data to a result object, but not returning it in the loadProducts call.

So just do

return result;

After making the $http request

Upvotes: 1

Related Questions