1

如何防止默认路由 Angular 2?在router subscribe中,我只得到路径名。我没有参与其中。Angular 2 中是否还有其他服务提供商可以获取路线更改事件?

app.component.js

(function (app) {

app.AppComponent = ng.core
        .Component({
            selector: 'my-app',
            templateUrl: 'app/views/main.html',
            directives: [ng.router.ROUTER_DIRECTIVES],
            viewProviders: [ng.http.HTTP_PROVIDERS]
        })
        .Class({
            constructor: [ng.router.Router, ng.http.Http, function (router, http) {

                   this.router.subscribe(function (pathname) {
                       //console.log(pathname);
                   });

            }],
        });

ng.router
        .RouteConfig([
          { path: '/login', component: app.LoginComponent, name: 'Login', useAsDefault: true },
          { path: '/todos', component: app.TodosComponent, name: 'Todos' },
        ])(app.AppComponent);

})(window.app || (window.app = {}));

引导.js

(function (app) {

    document.addEventListener('DOMContentLoaded', function () {
        ng.platform.browser.bootstrap(app.AppComponent, [ng.router.ROUTER_PROVIDERS, ng.core.provide(ng.router.LocationStrategy, { useClass: ng.router.HashLocationStrategy })]);
    });

})(window.app || (window.app = {}));
4

2 回答 2

0

您可以使用@CanActivate()来防止路由更改。

另请参阅Angular 2:将依赖项注入@CanActivate?对于当前的限制。

于 2016-03-04T11:04:21.333 回答
0

如果要CanActivate在纯 JS 中使用装饰器,请执行以下操作:

var Child1Component = ng.core.Component({
  selector:'test',
  template: '<div>Test</div>'
}).Class({
  onSubmit: function(){
    console.log('onSubmit');
  }
});

ng.router.CanActivate((next, prev) => {
  // The Child1Component component is instantiated
  return true;

  // The Child1Component component isn't instantiated
  // return false;
})(Child1Component);

例如,在启动时,该prev参数为 null,并且该参数next包含以下内容:

ComponentInstruction {
  urlPath: "child1",
  urlParams: Array[0],
  terminal: true,
  specificity: "2",
  params: Object…
}
于 2016-03-08T12:18:53.497 回答