7 - 8 条动态路线
7 - 8 dynamic routes
我有一个 Angular 应用程序,它应该能够根据用户创建新路线。假设用户 'johndoe' 注册了,那么应用应该创建一个路由:domain/johndoe
.
当然 /johndoe
路由应该提供一些关于特定用户的信息(如姓名、图像等)。
我正在使用 Google Cloud Hosting 和 Firestore 作为后端解决方案,到目前为止我的进展是将 Router
注入我的 AppComponent
构造函数,然后使用 unshift
router.config
上的函数。这种方法可行,但我必须将所有新路线 ('users') 存储到我的数据库中的单独文件中,然后每次有人导航到私人死记硬背时查询数据库(例如 domain/johndoe
).
是否有考虑到我的后端配置的美观且易于维护的解决方案?
您可以将用户名作为路由参数传递。在路线数组中
{ path: 'domain/:username', component: UserDetailsComponent }
在HTML中:
<a [routerLink]="['/domain', usernameVar]">
当有人点击 link 时,它将路由到 UserDetailsComponent。在组件中,
可以读取用户名。
username: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.username = params.username; // same as :username in route
});
// using username call the BE api and fetch data
}
有关路线参数的更多信息,请转至 https://angular.io/guide/router#route-parameters
如果您想根据授权路由到页面,请使用 authGuards。
https://angular.io/guide/router#canactivate-requiring-authentication
我有一个 Angular 应用程序,它应该能够根据用户创建新路线。假设用户 'johndoe' 注册了,那么应用应该创建一个路由:domain/johndoe
.
当然 /johndoe
路由应该提供一些关于特定用户的信息(如姓名、图像等)。
我正在使用 Google Cloud Hosting 和 Firestore 作为后端解决方案,到目前为止我的进展是将 Router
注入我的 AppComponent
构造函数,然后使用 unshift
router.config
上的函数。这种方法可行,但我必须将所有新路线 ('users') 存储到我的数据库中的单独文件中,然后每次有人导航到私人死记硬背时查询数据库(例如 domain/johndoe
).
是否有考虑到我的后端配置的美观且易于维护的解决方案?
您可以将用户名作为路由参数传递。在路线数组中
{ path: 'domain/:username', component: UserDetailsComponent }
在HTML中:
<a [routerLink]="['/domain', usernameVar]">
当有人点击 link 时,它将路由到 UserDetailsComponent。在组件中, 可以读取用户名。
username: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.username = params.username; // same as :username in route
});
// using username call the BE api and fetch data
}
有关路线参数的更多信息,请转至 https://angular.io/guide/router#route-parameters
如果您想根据授权路由到页面,请使用 authGuards。 https://angular.io/guide/router#canactivate-requiring-authentication