I have an Angular app which should be able to create new routes depending on users. Let's say user 'johndoe' registers, then the app should create a route: domain/johndoe
.
Of course the /johndoe
route should be provided with some info concerning the particular user ( like name, image etc.).
I am using Google Cloud Hosting and Firestore as back-end solutions, and my progress so far was to inject the Router
into my AppComponent
constructor and then use the unshift
function on the router.config
. That kind of works, but I would have to store all the new routes ('users') into my database in a separate file, and then query the database every time someone navigates to a private rote ( e.g. domain/johndoe
).
Is there a beautiful and easier to maintain solution, which takes into account my back-end configuration?
You can pass userName as a route parameter. In routes array
{ path: 'domain/:username', component: UserDetailsComponent }
in HTML:
<a [routerLink]="['/domain', usernameVar]">
When someone clicks on the link, it will route to UserDetailsComponent. In the component, the username can be read.
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
}
for more on route parameters, go to https://angular.io/guide/router#route-parameters
In case you want to route to the page based on authorization, use authGuards. https://angular.io/guide/router#canactivate-requiring-authentication