deepthan/blog-angular

Angular 路由跳转RouterLink

deepthan opened this issue · 0 comments

路由跳转RouterLink

接收路由地址:

<div routerLink="home">
</div>
<div [routerLink]="['home']">
</div>

路由地址的4种写法

和文件的相对路径、绝对路径用法一致

若当前路由为 http://localhost:4200/#/auth/login,想要跳转到home

home

http://localhost:4200/#/auth/login/home

当前路由 + 要跳转的路由。

./home
http://localhost:4200/#/auth/login/home

效果同home, 当前路由 + 要跳转的路由。

/home

http://localhost:4200/#/home

若以/开头则是绝对路径,跳转的地址为:http://localhost:4200/# + 绝对路径

../home

http://localhost:4200/#/auth/home

当前路由的上级路由 + 要跳转的路由。

动态路由写法

查看某个用户的信息,路由形式为user/:id/info其中id是动态变化的

routing.ts

const routes: Routes = [
  {
    path: "user/:id/info",
    component: DemoComponent
  }
];

html写法

<div [routerLink]="['/user', id, 'info']">动态路由</div>

id是在ts里面写的变量

路由传参

在路由后拼接

http://localhost:4200/auth/login?id=1

使用queryParams来传递,它接收一个对象

<div routerLink='home' 
     [queryParams]="{id:1}">queryParams传递参数</div>

在浏览器历史记录中添加

通过state进行传递,它的好处是不会在url上拼接不用担心长度过长问题。

<div routerLink='home' 
     [state]="{id: 1}">state传递参数
</div>