参考官网 《路由到视图》
假设我们定义了一个路由
{ path: 'heroes', component: HeroListComponent }
//页面不会刷新
<a routerLink="/heroes">Heroes</a>
注意:routerLink的作用是页面不会被重新加载,我们也可以配置原始的href
形式的,只不过页面此时会重新加载,也就是会产生一次刷新。
//页面会刷新
<a href="/heroes">Heroes</a>
this.router.navigate(['/heroes']);
this.router.navigateByUrl('/heroes');
假设我们定义了一个路由
{ path: 'hero/:id', component: HeroDetailComponent }
:id
令牌会为路由参数在路径中创建一个“空位”。在这里,这种配置会让路由器把英雄的 id 插入到那个“空位”中。会匹配类似localhost:4200/hero/15
。
<a [routerLink]="['/hero', hero.id]">
注意:
routerLink
的外层包裹了[]
,这样的html会识别出是个动态指令,会替换变量hero.id,并拼接成完整的链接。
router_link.d.ts 源码 注释
* For instance `['/team', teamId, 'user', userName, {details: true}]`
* means that we want to generate a link to `/team/11/user/bob;details=true`.
*
* Multiple static segments can be merged into one
* (e.g., `['/team/11/user', userName, {details: true}]`).
export declare class RouterLink
this.router.navigate(['/hero'+hero.id]);
this.router.navigateByUrl('/heroes'+hero.id);
假设我们的url形式如http://localhost:4200/settings/profile?name=lisi
,?后面有参数name,那么我们如何配置路由呢
<a routerLink='/settings/profile' [queryParams]="{name:'lisi'}">
profile</a>
通过[queryParams]
传参
NavigationExtras
对象 let name = 'lisi'
let navigationExtras: NavigationExtras = {
queryParams: { 'name': name}
};
// Navigate to the login page with extras
this.router.navigate(['/settings/profile'], navigationExtras);
我们可以简化配置:
不必设置中间变量,直接赋值一个NavigationExtras
对象结构的json
this.router.navigate(['/settings/profile'], { queryParams: { 'name': 'lisi' } });
this.router.navigateByUrl('/settings/password?name=zhangsan');
constructor(
private route: ActivatedRoute //引入ActivatedRoute
) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.name = params['name'];
//如果某个操作依赖name的值,需要在此处处理,不能放到括号外面,避免name的值尚未加载
doSomethingWithName();
});
}
注意:this.route.queryParams 返回值类型是Observable,需要用subscribe进一步处理,并且
获取参数是异步
的,因此,后续操作建议在获取参数后再进行。
如果想采用同步的方法获取参数,也是可行的,只要获取snapshot
属性
let snapshot: ActivatedRouteSnapshot = this.activatedRoute.snapshot;
this.name = snapshot.queryParams['name '];
snapshot
包含与当前组件相关的路由的当前瞬间信息。ActivatedRoute
也可用于遍历路由器的状态树。 ActivatedRouteSnapshot
也能用于遍历路由器状态树。
待续。。。
作为父组件,加载子组件ProfileSettingsComponent
和PasswordSettingsComponent
页面上有2个链接和2个按钮,链接测试routerLink
,按钮测试navigateByUrl()
和navigate()
。
浏览器中输入http://localhost:4200/settings
效果图如下:
import { Router } from '@angular/router';
import { Component } from '@angular/core';
@Component({
selector: 'settings-page',
template: `
`
})
export class SettingsComponent {
constructor(private router: Router) {
}
gotoPassword() {
console.log('gotoPassword')
this.router.navigateByUrl('/settings/password?name=zhangsan');
//this.router.navigate(['/settings/password'], { queryParams: { 'name': 'zhangsan' } });
}
gotoProfile() {
console.log('gotoProfile')
this.router.navigateByUrl('/settings/profile?name=lisi');
// this.router.navigate(['/settings/profile'], { queryParams: { 'name': 'lisi' } });
}
}
子组件,从路由中获取name参数,并显示至页面上。
触发profile链接效果如下:
此时url显示http://localhost:4200/settings/profile?name=lisi
import { ActivatedRoute } from '@angular/router';
import { Component } from '@angular/core';
@Component({
selector: 'settings-profile',
template: `
This is ProfileSettingsComponent Page:
name is {{name}}
`
})
export class ProfileSettingsComponent {
name;
constructor(private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.activatedRoute.queryParams.subscribe(
params => {
this.name = params['name'];
}
);
}
}
子组件,从路由中获取name参数,并显示至页面上
触发password链接效果如下:
此时url显示http://localhost:4200/settings/password?name=zhangsan
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'settings-password',
template: `
This is PasswordSettingsComponent Page:
name is {{name}}
`
})
export class PasswordSettingsComponent implements OnInit {
name;
constructor(private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.activatedRoute.queryParams.subscribe(
params => {
this.name = params['name'];
}
);
}
}
路由配置
import { PasswordSettingsComponent } from './password.settings.component';
import { ProfileSettingsComponent } from './profile.settings.component ';
import { SettingsComponent } from './settings.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';
export const ROUTES: Routes = [
{
path: 'settings',
component: SettingsComponent,
children: [
{ path: 'profile', component: ProfileSettingsComponent },
{ path: 'password', component: PasswordSettingsComponent }
]
}
];
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(ROUTES), FormsModule],
exports: [RouterModule]
})
export class AppRoutingModule { }
<!--第一级路由-->
<router-outlet></router-outlet>