Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the base URL dynamically in Angular 2 routing?

Currently, I have routing set up in my project. Every new user is redirected to:

localhost:4200/default-path/login

Once the user logs in, they're redirected to the home module, which has some child routes the user can navigate to.

localhost:4200/default-path/home
localhost:4200/default-path/home/account
localhost:4200/default-path/home/account/profile
localhost:4200/default-path/home/dashboard

... and so on.

Now, the part in bold is already set up in the home module, and doesn't need further editing. However, I'd like to change default-path to something else.

Say, each user can belong to one of three projects: Project blue, red or green. This information is available only after the user submits their credentials and hits the login button.

What I'd like for the routes to say after login is:

localhost:4200/project-blue/home
localhost:4200/project-red/home
localhost:4200/project-green/home

Bear in mind, the parts in bold are NOT different modules with different associated components, they're just constants I'd like to see in the URL.

Currently, my <base> tag in the index is like <base href='/'> I'm trying to edit this attribute. What I've got is something like:

processLoginSuccess(loginTicket): void {
    const routeName = loginTicket.baseUrl // returns 'project-red'
    let b = document.getElementsByTagName('base')[0]
    b.setAttribute('href', routeName )

    this._router.navigate(['/home']);
}

But this doesn't seem to work.

Any ideas?

like image 959
Snowman Avatar asked Jan 04 '23 18:01

Snowman


1 Answers

Instead of setting the base element's href value, you can set the base URL programmatically, by providing for APP_BASE_HREF with your custom operation.

This has been already discussed here: https://stackoverflow.com/a/41674411/415790

like image 200
Krishnan Avatar answered Jan 08 '23 08:01

Krishnan