在Angular 2+中,路由导航问题可以通过以下几种方法解决:
Home
About
import { Router } from '@angular/router';
constructor(private router: Router) {}
navigateToHome() {
this.router.navigate(['/home']);
}
navigateToAbout() {
this.router.navigate(['/about']);
}
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// 判断用户是否已登录,如果未登录则导航到登录页
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
template: `{{userId}}
`
})
export class UserComponent {
userId: string;
constructor(private route: ActivatedRoute) {
this.userId = this.route.snapshot.params['id'];
}
}
这些方法可以根据具体的需求和场景来使用,希望能对你有帮助!