When Custom Route Provider is not a valid function

This question has been revised since this morning.

I am working with two distinct modules, 'admin' and 'authorization'. Within the provider block of the authorization module, I utilize $routeProvider to add an identical route to all route definitions.

Let's start with admin.js:

angular.module('authorization', [])
    .provider('$appRoute', function () {
        this.$get = function($routeProvider) {
            var universalResolves = {authorize: function($authorization) {
                    return $authorization.authorize();
                }};

            var extendedRouter = angular.extend({}, $routeProvider, {
                when: function(path, route) {
                    route.resolve = (route.resolve) ? route.resolve : {};
                    angular.extend(route.resolve, universalResolves);
                    $routeProvider.when(path, route);
                    return this;
                }
            });

            return new extendedRouter();
        }
    })
    .factory('$authorization', ['$http', '$location', function($http, $location) {

        var $authorization = {};

        $authorization.authorize = function() {

            var path = $location.path();

            return promise = $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                var data = response.data;
                if (response.data.result === 'NOT_AUTHORIZED') {
                    throw "NOT_AUTHORIZED";
                }

                return data;
            });

        };

        return $authorization;
    }]);

Now let's move on to my admin module:

angular.module('admin', ['ngRoute', 'ngSanitize', 'ngCsv'
        , 'authorization'
    ])

    .controller('mainCtrl', function() {

    })
    .config(['$routeProvider', '$appRouteProvider', function($routeProvider, $appRouteProvider) {

        // The previous definition that needs to be updated to use $appRouteProvider
        $routeProvider.when('/login', {
            templateUrl: '/login/auth.html',
            controller: 'loginCtrl'
        });

        $appRouteProvider.when('/page', {
            templateUrl: 'page.tmpl.html',
            controller: 'pageCtrl'
        });

Unfortunately, an error occurs:

Error: [$injector:modulerr] Failed to instantiate module app due to:
$appRouteProvider.when is not a function
@https://localhost:8443/admin.js:87:9
invoke@https://localhost:8443/js/angular/angular.js:4718:16
runInvokeQueue@https://localhost:8443/js/angular/angular.js:4611:11
loadModules/<@https://localhost:8443/js/angular/angular.js:4620:11
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
loadModules/<@https://localhost:8443/js/angular/angular.js:4618:40
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
createInjector@https://localhost:8443/js/angular/angular.js:4523:19
doBootstrap@https://localhost:8443/js/angular/angular.js:1758:20
bootstrap@https://localhost:8443/js/angular/angular.js:1779:12
angularInit@https://localhost:8443/js/angular/angular.js:1664:5
@https://localhost:8443/js/angular/angular.js:31763:5
j@https://localhost:8443/js/jquery/jquery.min.js:2:29566
g/</k<@https://localhost:8443/js/jquery/jquery.min.js:2:29882

The $appRouteProvider is being recognized, but only the this.$get() method. Can anyone provide assistance?

Answer №1

Discussing the issue at hand, it appears that the $appRoute provider does not have any methods exposed on itself other than $get. Therefore, it functions as an empty api config provider object.

When utilizing the base provider recipe, the $get method is utilized to offer a function for generating the service, and the this from the provider is utilized to attach additional config functions that can set data for the $get function to utilize later on.

Referencing the Angular provider documentation:

myApp.provider('unicornLauncher', function UnicornLauncherProvider() {
  var useTinfoilShielding = false;

  // Provider config API method.
  this.useTinfoilShielding = function(value) {
    useTinfoilShielding = !!value;
  };

  this.$get = ["apiToken", function unicornLauncherFactory(apiToken) {

    // Assuming the UnicornLauncher constructor was modified to also accept and utilize the useTinfoilShielding argument
    return new UnicornLauncher(apiToken, useTinfoilShielding);
  }];
});

If you wish to introduce additional methods on the provider, you can utilize this.when = ... or Angular.extends(this, ....), for example.

Answer №2

I decided to go for a more straightforward approach instead of extending the route provider.

Within my main module, I made adjustments to all routes using the following code:

angular.module('app'[])
    .run(function($route) {
        var keys = Object.keys($route.routes);
        keys.forEach(function(key) {
            var alteredRoute = $route.routes[key];

            // if there's already a resolve function defined, don't overwrite it, just add a new one
            alteredRoute.resolve = key.resolve?key.resolve:{};
            alteredRoute.resolve.authorize = function($authorization) {
                return $authorization.authorize();
            }

            $route[key] = alteredRoute;
        });
     });

This method functions because the routes had already been set in other modules' .config() sections, which were executed before the run() block. It may not be the prettiest solution, but it gets the job done.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting a basic jQuery UI tooltip to function properly

I attempted to recreate the demo found on this website: http://jqueryui.com/tooltip/#default Here is the HTML code I used: <h3 title='this is the title of hello world'>hello world</h3> And here is the JavaScript code: $(document). ...

Guide to streaming audio files using vue.js

I am attempting to incorporate an audio file into my vue.js project using the following code: import sound from '../../recordings/sound.mp4' const audio = new Audio(sound) audio.play() Although this method works perfectly fine, I have encounter ...

What is the best way to refresh the script located within the head tag of an index.html file in an Angular

I've been looking for solutions, but I can't seem to find one. In my index.html file, I've placed some script within the head tag (even above the </body> tag) and included a $(document).ready function. The issue I'm facing is th ...

Unraveling the mysteries of this PHP-generated object

Need help with iterating over a JSON object generated by PHP code in response to a web service request. Looking for guidance on rendering sub-objects in a select list, especially those with value indexes. Can someone provide assistance on populating a sel ...

Unable to display the Error 404 Component within a nested Component using React Router

When attempting to display the Error component if no matches are found, I encountered an issue - selecting a non-existing route only leads to a blank page. In the example, the Main component adds a sidebar menu and renders all its children inside it. If ...

Is there a way in JavaScript to track changes in CSS properties such as transitioning from "display:none" to "display:block"?

Is there a way to detect when the CSS property "display" of an image is changed by another JavaScript script or function and then execute some JS code? I tried using $(this).bind('propertychange', function(){}) but it doesn't work, and setIn ...

How to send URL parameters to a different page with the help of express and Node.js

Hey there, I'm currently working on a chat app which you can check out here. I'm in the process of enabling users to join specific rooms by typing in a URL like , assuming they are logged in. I manage user login and signup with passwords. Here&ap ...

Checking authentication globally using Vue.js

In the main blade file, I have the following code snippet: <script> window.App = {!! json_encode([ 'csrfToken' => csrf_token(), 'user' => Auth::user(), 'signedIn' => Auth::check() ...

Update the inputs following the filtering or searching of issues in VueJS

As a newcomer to VueJS, I find myself struggling with a particular function and lack the experience to fully grasp it. To address my confusion, I have formulated a question (which may be similar to others). For instance, I utilized the computed propert ...

Vue: Utilizing computed properties to monitor changes in offsetHeight of elements

I am working on a component that requires an array of 50 objects to be passed as a prop. <template> <div v-for="(item,index) in items" ref="items" :key="index"gt; // </div> </template> props: ...

"Identify the protocol name (string) based on a specific port number in TCP/UDP communication

Is there a built-in function in any web-oriented language to return protocol names based on port numbers? For example, if we have the following code: protocol = get_protocol_name(22) print protocol We would expect it to print out "ssh". A more detailed ...

Failure to upload file using AngularJS

Below is the code snippet for file uploading: Here is the HTML code used to select and upload the file: <form ng-click="addImportFile()" enctype="multipart/form-data"> <label for="importfile">Import Time Events File:</label><br&g ...

Delay calls to JavaScript functions, ensuring all are processed in order without any being discarded

Is there a way for a function to limit the frequency of its calls without discarding them? Instead of dropping calls that are too frequent, is it possible to queue them up and space them out over time, say X milliseconds apart? I've explored concepts ...

Errors encountered by the Chrome extension

Hey there, I've recently delved into creating a chrome extension but hit a roadblock. My issue revolves around the service worker registration failing and encountering errors related to undefined properties. https://i.stack.imgur.com/bGzB4.png The c ...

"Troubleshooting: Why Won't insertAfter Function Work with

I have a p Element that I want to wrap inside a span tag. Then, I need to insert it after another p tag with the id output. Despite my attempts, the insertAfter function is not working as expected. $mytext = $("p#test").html(); $myspan = "<span styl ...

iOS unique identifier with Phonegap and AngularJS

I'm working on an AngularJS and PhoneGap app, and I need a way to generate a unique identifier for each user of the app. It seems like getting the phone number from the device is not possible, can anyone confirm this? If retrieving the phone number ...

Tips for preventing the use of website URLs as variables in jQuery ajax() calls:

Having some trouble. For example: $(document).ready(function () { $("#btnSend").click(function () { var noti_p = { url: "Pusher_Controller.ashx", data: "&appname=" + $("#selt1").val() + "&title=" + $("#title"). ...

Guide for integrating images in React Native

I am struggling to display images in a carousel properly. I attempted to require them using JSON like this {"Image": require("$PATH")} or in a js file within the ParallaxImage tag, but nothing seems to work... Item Creator _renderItem ...

Having difficulty with loading JSON data into jqGrid

Explaining my jqGrid definition: . . . datatype: 'json', //Setting the data type to JSON url:'<%=request.getContextPath()%>/servlet/AjaxManager?mode=9999&beginindex=0&totallimit=10&colname=policyname&sorttype=asc&apos ...

Steps for assigning a texture to a child Mesh within an Object3D

My Object3D was imported in the following manner: var customObject; // defining a global object var loader = new THREE.ObjectLoader(); loader.load('path/to/object3d.json', function(object) { customObject = object; scene.add(customObject ...