0

I am new to Angular js. I am using version 1.6.

I am trying to read data from a local json file using a factory to display information. I keep getting this error:

plotFactory.getPlots(...).then(...).error is not a function

My local file structure is

App/scripts/data/plots.json

App/scripts/app.js

App/scripts/main.controller.js

App/scripts/plot.factory.js

App/index.html

main.controller.js

angular
    .module('myApp')
    .controller('mainController',function ($scope, $http, plotFactory) {

        $scope.plots = [];

        //Method 1
        plotFactory.getPlots().then(function successCallback (resp) {
            console.log("If you reading this , momma we made it.")
            $scope.plots = resp.data;
        }).error(function (error) {
            console.log(error)
        });

    });

plot.factory.js

angular
.module('myApp')
.factory('plotFactory', function($http) {

    function getPlots() {
        return $http.get('data/plots.json');
    }

    return {
        getPlots: getPlots
    }
});

index.html

<body ng-app="myApp" ng-controller="mainController">

    <a class="accessibility" href="#main-content" accesskey="S">Skip to Content</a>
    <div class="loading-screen">
        <img src="_assets/images/pentair_logo.png" width="359" height="100" alt="Emerson" />
    </div>
    <div id="wrapper">
        <header>
            <div class="container-fluid">
                <a href="#" class="logo"><img class="logoimg" src="_assets/images/pentair_logo.png" alt="Pentair" /><span>Interactive Sales Presentation</span></a>
                <a href="#" class="menu-opener pull-right"><span></span></a>
            </div>
        </header>
        <div class="menu-wrapper">
            <div class="mobile-menu">
                <ul class="collapsible">
                    <li ng-repeat="mobileMenu"><a href={{mobileMenu.url}}>{{mobileMenu.name}}</a></li>
                </ul>
            </div>
        </div>

        <div class="main-content">
            <div class="container-fluid">
                <div class="content-wrapper">
                    <img src="_assets/images/ui/Main_Background_edit.jpg" class="map-overlay" width="1024" height="768" alt="Oil and Gas" />
                    <div class="map-wrapper">
                        <div class="map-control level-01 panzoom">
                            <img src="_assets/images/ui/Main_Background_edit.jpg" class="map-bg" width="1024" height="768" alt="Oil and Gas" />
                            <div class="overlay"></div>

                            <!-- All Map Points -->
                            <div ng-repeat="plot in plots">
                                <a href={{plot.url}} class="plot level1 arrow-head flip {{plot.sid}}"><div><span class="title">{{plot.name}}</span><span class="number">+</span></div></a>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <footer>
            <div class="container-fluid">
                Footer
            </div>
        </footer>

    </div>


    <!-- Load Angular Dependencies -->


    <!-- Async load of Javascript  -->
    <script type="text/javascript">
        function loadJS(e) { var t = document.createElement("script"); t.type = "text/javascript", t.async = !0, t.src = e; var n = document.getElementsByTagName("head")[0]; n.appendChild(t) };
        loadJS('_assets/js/all.min.js');
    </script>

    <!-- In case javascript is disabled -->
    <noscript>
        <script type="text/javascript" src="_assets/css/all.min.js"></script>
    </noscript>

    <!-- Main App -->

    <script type="text/javascript" src="Angular/angular.min.js"></script>

    <script src="Angular/angular-route.min.js"></script>
    <script src="scripts/app.js"></script>

    <script src="scripts/plot.factory.js"></script>
    <script src="scripts/main.controller.js"></script>

</body>

I have tried a few different paths none work. My data WILL read however if I leave the json data as a variable inside my factory... but I am trying to separate data from controllers for good practice. My guess is that the function is causing error: not a function because of the path not returning anything valid, thus failing the cued up .then function. Is it the file path in my factory's $http.get() request? Or am I missing something else?


updated the get function and callbacks.

plotFactory.getPlots().then(function successCallback(response) { 
    //this callback will be called asynchronously
   //when the response is available 
   $scope.plots = response.data;
   console.log("Method 2 worked!") 
},function errorCallback(response) { 
   console.log("We got a problem...") 
}); 

Still getting a 404 not found for data/plots.json. Could this be reference error?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Ares
  • 411
  • 8
  • 15
  • _"not a function because of the path not returning anything"_, no it is giving that error because there is no `error()` function for angular promises anymore. Look at the [documentation](https://docs.angularjs.org/api/ng/service/$http#general-usage) on the format to use – Patrick Evans Dec 27 '16 at 20:05
  • @PatrickEvans Thanks for that. I updated the get function and callbacks. plotFactory.getPlots().then(function successCallback(response) { //this callback will be called asynchronously //when the response is available $scope.plots = response.data; console.log("Method 2 worked!") }, function errorCallback(response) { console.log("We got a problem...") }); Still getting a 404 not found for data/plots.json . Could this be reference error? – Ares Dec 27 '16 at 20:33

4 Answers4

0

The problem is with your file path. If you are running the app in your local server, mention the path properly. Assuming you are running in your localhost port 3000, it should be something like:

$http.get("localhost:3000/myApp/data/plots.json");

Or if you have opened the index.html in the browser and testing it (which doesn't work in Chrome though but works in FireFox) mention the path to json file from the controller file like :

$http.get("../data/plots.json")

assuming it is in the same folder where 'scripts' folder is present.

Supradeep
  • 3,246
  • 1
  • 14
  • 28
0

URLs for in-browser JavaScript are resolved relative to the URL that the HTML document the script is running against, not against the URL for the script itself.

Since the HTML document is at App/index.html you need scripts/data/plots.json, not data/plots.json

(This assumes that Angular isn't messing about with the History API to change the URL).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks. still getting the 404 though. My request looks like this : $http({ method: 'GET', url: '/scripts/data/plots.json' }) The console error is : GET http://localhost:51998/scripts/data/plots.json 404 (Not Found) Maybe origin is wrong? Or alternatively use an absolute path? – Ares Dec 27 '16 at 21:17
  • @AdanHuerta — What HTTP server are you using? – Quentin Dec 27 '16 at 21:18
0

Still getting a 404 not found for data/plots.json. Could this be reference error?

Use scripts/data/plots.json

Also use .catch instead of .error.

For more information, see Why are angular $http success/error methods deprecated? Removed from v1.6?

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

Thank you for your input. Turns out there were two parts to this solution, one was the file path.

Part 1:

 return $http({
                url: "/scripts/data/plots.json",
                method: 'GET'            
            })

Uses the correct path.

Part 2: Was trickier for me. I apologize for not including this in the question. I am using Visual Studio 2013 and it utilizes a Web.config file that needed to set to allow certain types of JSON files. I had no idea until my senior dev pointed it out. I'll keep this in mind for future inquiries.

Thanks again !

    <?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />

    </system.web>

  **<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
  </system.webServer>**

</configuration>
Ares
  • 411
  • 8
  • 15