2016-03-04 112 views
1

我怎么能防止默认在角2中的路由?在路由器订阅,我只得到路径名。我没有得到它的事件。角2中是否有其他服务提供商获取路线更改事件?防止默认路由 - 角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 = {})); 

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

@ThierryTemplier你能帮助解决这个问题吗? –

+0

这是不是很清楚你想要做什么。您是否想要阻止具有点击处理程序的链接的默认行为? – Ludohen

+0

'$ scope。$ on('$ routeChangeStart',function(event,next,current){})'在角度1中,_ $ routeChangeStart_给出了路由变更事件的权利?同样的事情,我需要在这里角2.我用路由器订阅获取路线变化。但我只有路径名。 –

回答

0

如果你想使用纯JS的CanActivate装饰,您执行以下操作:

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… 
} 
+0

它是100%的工作。我是否需要为每个子组件添加'CanActivate'?我可以为** AppComponent **添加'CanActivate',这样我就可以每次在路由更改时监听,而无需为每个子组件添加'CanActivate'? –

+0

太棒了!必须为每个组件定义'CanActivate',因为它允许组件被实例化或不被...实例化。 –

+0

好的。一切完成。非常感谢你的帮助。我从你身上学到了很多东西。谢谢 –

0

可以使用@CanActivate()防止路由变化。

另请参阅Angular 2: Inject a dependency into @CanActivate?了解当前限制。

+0

你可以给一个** CanActivate **的Javascript代码样例吗? –

+0

目前尚不清楚你的问题是什么。见上面的评论。链接的问题有代码的答案。你也可以查看https://github.com/angular/angular/issues/4112#issuecomment-153811572 –

+0

我的问题很简单。我需要在登录后防止后退按钮导航。在角度1中,** $ routeChangeStart **在路由更改时给出**事件,接下来的是prev **。同样的事情,我需要在这里角2.我该怎么做? –