1.配置動態路由
const routes: Routes = [ {path: 'home', component: HomeComponent}, {path: 'news', component: NewsComponent}, {path: 'newscontent/:id', component: NewscontentComponent}, { path: '', redirectTo: '/home', pathMatch: 'full' } ];
2.跳轉傳值
<a [routerLink]="[ '/newscontent/',aid]">跳轉到詳情</a>
<a routerLink="/newscontent/{{aid}}">跳轉到詳情</a>
3.獲取動態路由的值
import { ActivatedRoute} from '@angular/router';
constructor( private route: ActivatedRoute) { }
ngOnInit() { console.log(this.route.params); this.route.params.subscribe(data=>this.id=data.id); }
動態路由的 js 跳轉
1. 引入
import { Router } from '@angular/router';
2.初始化
xport class HomeComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { } goNews(){ // this.router.navigate(['/news', hero.id]); this.router.navigate(['/news']); } }
3.路由跳轉
this.router.navigate(['/news', hero.id]);
路由 get 傳值 js 跳轉
1. 引入 NavigationExtras
import { Router ,NavigationExtras} from '@angular/router';
2.定義一個 goNewsContent 方法執行跳轉,用 NavigationExtras 配置傳參。
goNewsContent(){ let navigationExtras: NavigationExtras = { queryParams: { 'session_id': '123' }, fragment: 'anchor' }; this.router.navigate(['/news'],navigationExtras); }
3.獲取 get 傳值
constructor(private route: ActivatedRoute) { console.log(this.route.queryParams); }