Search code examples
javascriptangularjsangularjs-routing

AngularJs - route resolve function does not recognize factory


I'm using AngularJS 1.6.1, and I'm trying to do a simple task that I have already done before (long time ago), but for some reason I can't realize what is happening this time.

Basically I want to call my REST service, but when I pass my factory in the parameters of the resolve function, it stops working.

I made a simple example to post here in order to make it easier:

index.html

<html ng-app="TesteApp">
<head>
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>

  <script src="app.js"></script>
</head>
<body>
    <div class="ng-view">
    </div>
</body>

view.html

<h1>DONE</h1>

app.js

angular.module('TesteApp', ['ngRoute']);

angular.module('TesteApp').controller('testeController', function($scope, resultSet) {
   console.log("1");
});

angular.module('TesteApp').config(function ($routeProvider) {
    $routeProvider.when("/", {
        templateUrl: "view.html",
        controller: "testeController",
        resolve: {
            resultSet: function(callApi) { // seems like 'callApi' is not being recognized?!
                //If I return the fixed list below and take the 'callApi' parameter above, it works.
                //return "[{id:1, nome: 'teste'}, {id:2, nome: 'teste2'}]";
                return callApi.getResult(); 
            }
        }
    });
});

angular.module("TesteApp").factory("callApi", function ($http, config) {
    var _getResult = function () {
        return $http.get("http://localhost:8080/result");
    };

    return {
        getResult: _getResult
    };
});

Like I said in the comment, it seems like 'callApi' is not recognized.

The console does not print errors and the <div class="ng-view">is not replaced by <h1>DONE</h1>, and no request is in fact done.


Solution

  • Update

    Its wiered(as it isn't throwing any error in console), but config dependency injected inside callApi wasn't mentioned anywhere, so it is failing there. Removed that unknown dependency will fix your issue.

    Demo Here


    You had wrong service method name. Instead of getArticles call getResult.

    return callApi.getArticles();
    

    should be

    return callApi.getResult();