Prevent Default Routing - Angular 2

眉间皱痕 提交于 2020-01-06 01:54:09

问题


How can I prevent default the routing in angular 2? In router subscribe, I get only the path name. I am not getting event in it. Is there any other service provider in angular 2 to get the route change event?

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 = {}));

boot.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 = {}));

回答1:


If you want to use the CanActivate decorator in plain JS, you do the following:

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);

For example, at startup, the prev parameter is null and the next one contains the following:

ComponentInstruction {
  urlPath: "child1",
  urlParams: Array[0],
  terminal: true,
  specificity: "2",
  params: Object…
}



回答2:


You can use the @CanActivate() to prevent route change.

See also Angular 2: Inject a dependency into @CanActivate? for current limitations.



来源:https://stackoverflow.com/questions/35794034/prevent-default-routing-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!