1 接上一节,还记得有个
{path: 'newscontent/:id', component: NewscontentComponent},
那么,newscontent组件如何获取路由传递过来的id呢,上代码(newscontent.component.ts):
import { Component, OnInit } from '@angular/core';
import {Router,ActivatedRoute,NavigationExtras} from '@angular/router';
@Component({
selector: 'app-newscontent',
templateUrl: './newscontent.component.html',
styleUrls: ['./newscontent.component.css']
})
export class NewscontentComponent implements OnInit {
constructor(private route:ActivatedRoute,private router:Router) { }
ngOnInit() {
//获取总路由传过来的id值
console.log(this.route.params);
}
goNews(){
// 不带参数从newscontent组件跳转到news组件
this.router.navigate(['/news']);
}
goNewsWithParam()
{
//get传参
let navigationExtras:NavigationExtras = {
queryParams:{
'sid':'123'
},
fragment:'anchor'
};
this.router.navigate(['/news'],navigationExtras);
}
}
2 带参数从newscontent组件跳转到news组件后,news组件怎么接收参数呢,上代码news.component.ts:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
constructor(private route: ActivatedRoute) {
console.log(this.route.queryParams);
}
ngOnInit() {
}
}