dislikesAppleCores dislikesAppleCores - 1 year ago 124
AngularJS Question

How do I log what ngRoute requests are being made?

I'm porting over a decently sized Angular 1.6 app from an old build system(s) onto Yarn/Webpack.

We're using the standard ngRoute/large promise chain for our routing. As I've been working my way through getting all the imports & dependencies right, I keep getting this error:


WARNING: Tried to load angular more than once.


According to this SO post, there are a variety of potential causes. But the one that's helped me get certain pages of the app working was resolving all the templateUrl's to be correct. Both in module definitions, and when using ng-include's in the any template.

Thing is, some of these component chains are massive. There's conditional ng-including all over the place. So it would be extremely useful if, instead of having to manually search through these huge component trees, at the end of the big promise chain, when anything doesn't match and hits here:

.otherwise({
redirectTo: '/',
template: '<public-home></public-home>'
});


I want get feedback on what was attempted, and if possible, where that attempt came from. This would help me locate where the errant includes are.

So my problem is being unable to identify improperly resolved route requests, and I'd like to just be able to log or record feedback about what's being routed.

So hopefully that's specific enough, and this is my current best guess at resolving the situation. But if there are better ways to figure out this business around angular reloading itself, I'm all ears!

Answer Source

For Angular 1 If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        // handle route changes     
    });
    // or try this
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
     //..do something
     //event.stopPropagation();  //if you don't want event to bubble up 
    });

});

for angular 2 new router

constructor(router:Router) {
  router.events.subscribe(event:Event => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

old

Inject the Router and subscribe to route change events

import {Router} from 'angular2/router';

class MyComponent {
  constructor(router:Router) {
    router.subscribe(...)
  }
}

NOTE

For the new router, don't forget to import NavigationStart from router module

import { Router, NavigationStart } from '@angular/router';

because if you don't import it instanceof will not work and an error NavigationStart is not defined will rise.

See also

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download