我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
只需在AppRoutingModule上进行更改
@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
exports: [RouterModule]
})
其他回答
下面的方法可以帮你解决棘手的问题。
// in constructor of your app.ts with router and auth services injected
router.subscribe(path => {
if (!authService.isAuthorised(path)) //whatever your auth service needs
router.navigate(['/Login']);
});
不幸的是,这在路由过程中比我想要的晚些时候重定向。在重定向之前调用原始目标组件的onActivate()。
你可以在目标组件上使用@CanActivate装饰器,但这是a)不集中的,b)不能从注入的服务中受益。
如果有人能提出一种更好的方法,在路由提交之前对其进行集中授权,那就太好了。我相信一定有更好的办法。
这是我当前的代码(我如何改变它来监听路由变化?):
import {Component, View, bootstrap, bind, provide} from 'angular2/angular2';
import {ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';
import {Location, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import { Todo } from './components/todo/todo';
import { About } from './components/about/about';
@Component({
selector: 'app'
})
@View({
template: `
<div class="container">
<nav>
<ul>
<li><a [router-link]="['/Home']">Todo</a></li>
<li><a [router-link]="['/About']">About</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
</div>
`,
directives: [RouterOutlet, RouterLink]
})
@RouteConfig([
{ path: '/', redirectTo: '/home' },
{ path: '/home', component: Todo, as: 'Home' },
{ path: '/about', component: About, as: 'About' }
])
class AppComponent {
constructor(location: Location){
location.go('/');
}
}
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'})]);
在Angular 2中,你可以订阅(Rx事件)一个Router实例。 你可以这样做
class MyClass {
constructor(private router: Router) {
router.subscribe((val) => /*whatever*/)
}
}
编辑(从rc.1开始)
class MyClass {
constructor(private router: Router) {
router.changes.subscribe((val) => /*whatever*/)
}
}
编辑2(从2.0.0开始)
请参见:路由器。活动文档
class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
如果你试图访问当前路由,同时监听路由变化:
router.events.pipe(filter(r=>r instanceof NavigationEnd)).subscribe(r=>{
console.log((r as NavigationEnd).url);
});
更清晰的方法是继承RouteAware并实现onNavigationEnd()方法。
它是一个名为@bespunky/angular-zen的库的一部分。
NPM install @bespunky/angular-zen 让你的AppComponent扩展RouteAware并添加一个onNavigationEnd()方法。
import { Component } from '@angular/core';
import { NavigationEnd } from '@angular/router';
import { RouteAware } from '@bespunky/angular-zen/router-x';
@Component({
selector : 'app-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent extends RouteAware
{
protected onNavigationEnd(event: NavigationEnd): void
{
// Handle authentication...
}
}
RouteAware还有其他好处,比如: ✨任何路由器事件都可以有处理程序方法(Angular支持的路由器事件)。 ✨使用这个。路由器访问路由器 ✨使用这个。访问激活路由的路由 ✨使用this.componentBus访问RouterOutletComponentBus服务
如果您只是想检查路由/查询参数更改,如localhost:4200/users/1?编辑=1到localhost:4200/users/2?Edit =0你可以像下面这样使用可观察的参数。
import { ActivatedRoute, Params } from '@angular/router';
export class SomeClass implements OnInit {
paramFromRoute;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.paramFromRoute = this.route.snapshot.params['paramName']; // this one is required for getting it first time
this.route.params.subscribe((params:Params)=>{
this.paramFromRoute = params['paramName'] // whenever route is changed, this function will triggered.
});
// for queryParams you can subscribe to this.route.queryParams
}
}