Angular 2 - 我试图使用router.parent.navigate导航到另一条路线。
但是,我得到的错误是:" EXCEPTION:TypeError:无法读取属性'导航' of null"在我的控制台日志中。
这是我目前的代码:
import {Component, View, bootstrap, bind, provide} from 'angular2/angular2';
import {Router, 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';
import {AuthService} from './authService';
@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' }
])
export class AppComponent {
constructor(_router: Router, _authService: AuthService, _location: Location){
_router.subscribe((val) => {
_authService.isUserLoggedIn().then((success) => {
//This part below is not working:
_router.parent.navigate(['/About']);
});
})
}
}
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'}), AuthService]);
答案 0 :(得分:0)
我认为你应该使用ngOnInit方法。
export class AppComponent implements OnInit {
constructor(router: Router, authService: AuthService, location: Location){
}
ngOnInit(){
this.router.subscribe((val) => {
this.authService.isUserLoggedIn().then((success) => {
//This part below is not working:
this.router.parent.navigate(['/About']);
});
})
}
}