ActivatedRoute
实例获取路由参数// queryParams 传递的是一个对象
<a [routerLink]="[ '/endpage/']" [queryParams]="{name:'huangbiao',age:30}">endpagea>
const routes: Routes = [
{ path: 'endpage', component: EndPageComponent }
];
url的地址是
http://localhost:4200/endpage?name=huangbiao&age=30
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-end-page',
templateUrl: './end-page.component.html',
styleUrls: ['./end-page.component.scss']
})
export class EndPageComponent implements OnInit {
constructor(public route:ActivatedRoute) { }
ngOnInit() {
console.dir(this.route);
debugger
this.route.params.subscribe((data)=>{
console.log(data); // 打印的是一个对象,key为name和age
});
}
}
获取参数要依赖注入
route:ActivatedRoute
对象
// 第一个参数对应路由的name,第二个参数对应路由的age
<a [routerLink]="[ '/endpage/', 'huangbiao','30' ]">endpagea>
const routes: Routes = [
{ path: 'endpage/:name/:age', component: EndPageComponent }
];
url地址是
http://localhost:4200/endpage/huangbiao/30
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-end-page',
templateUrl: './end-page.component.html',
styleUrls: ['./end-page.component.scss']
})
export class EndPageComponent implements OnInit {
constructor(public route:ActivatedRoute) { }
ngOnInit() {
console.dir(this.route);
debugger
this.route.params.subscribe((data)=>{
console.log(data); // 打印的是一个对象,key为name和age
});
}
}
获取参数要依赖注入
route:ActivatedRoute
对象
this.router.navigate(['/newscontent/','1243'])
//this.router.navigate(['/home']);
如果是动态路由,则路由后面的
/
是不能少的
url 跳转地址http://localhost:4200/newscontent/1243
const routes: Routes = [
{ path: 'endpage', component: EndPageComponent }
];
import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router';
@Component({
selector: 'app-end-page',
templateUrl: './end-page.component.html',
styleUrls: ['./end-page.component.scss']
})
export class EndPageComponent implements OnInit {
constructor(public router:Router) { }
ngOnInit() {
console.dir(this.route);
debugger
this.route.params.subscribe((data)=>{
console.log(data); // 打印的是一个对象
});
}
}
this.router.navigate(['/news'],{
queryParams:{
aid:123
}
});
如果是动态路由,则路由后面的
/
是不能少的
url 跳转地址http://localhost:4200/news?aid=123
const routes: Routes = [
{ path: 'endpage', component: EndPageComponent }
];
import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router';
@Component({
selector: 'app-end-page',
templateUrl: './end-page.component.html',
styleUrls: ['./end-page.component.scss']
})
export class EndPageComponent implements OnInit {
constructor(public router:Router) { }
ngOnInit() {
console.dir(this.route);
debugger
this.route.params.subscribe((data)=>{
console.log(data); // 打印的是一个对象
});
}
}