如何记录发出的 ngRoute 请求?

How do I log what ngRoute requests are being made?

我正在将一个大小合适的 Angular 1.6 应用程序从旧的构建系统移植到 Yarn/Webpack。

我们使用标准 ngRoute/large 承诺链进行路由。由于我一直在努力使所有导入和依赖关系正确,我不断收到此错误:

WARNING: Tried to load angular more than once.

根据 this SO post,有多种潜在原因。但是帮助我使应用程序的某些页面正常工作的方法是将所有 templateUrl 解析为正确。在模块定义中,以及在任何模板中使用 ng-include 时。

事实是,其中一些组件链非常庞大。到处都有条件 ng-including。因此,如果无需手动搜索这些庞大的组件树,在大承诺链的末尾,当任何内容不匹配并点击此处时,这将非常有用:

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

我想获得有关尝试内容的反馈,如果可能的话,还想知道该尝试的来源。这将帮助我找到错误包含的位置。

所以我的问题是无法识别未正确解决的路由请求,我希望能够记录或记录有关正在路由的内容的反馈。

所以希望这足够具体,这是我目前对解决问题的最佳猜测。但是,如果有更好的方法来围绕 angular 重新加载自身来解决这个问题,我洗耳恭听!

对于Angular 1 如果您不想将手表放在特定的控制器中,您可以在 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 新路由器

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

注入路由器并订阅路由更改事件

import {Router} from 'angular2/router';

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

注意

对于新路由器,不要忘记从 router 模块导入 NavigationStart

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

因为如果你不导入它 instanceof 将无法工作并且会出现错误 NavigationStart is not defined

另见