简体   繁体   中英

Angular 4/5 - Change base href dynamically

I am working on a multi-tenant application with Ex URL: " https://example.com/ { portalID }/Login" where portalID changes customer to customer. So the initial login looks like this.
https://example.com/portalId/Login
In the login page, I have a text box and a button. So the text box accepts portalId and onclick, I want to change the portalId in the URL without page reload.

Code:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent } from './';
import { getBaseLocation } from './shared/common-functions.util';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
  ],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    {
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation
    },
  ]
})
export class AppModule { }

export function getBaseLocation() {
    let basePath = sessionStorage.getItem('portalId') || 'portalId'; // Default
    return '/' + basePath;
}

In production build, I was setting portalID as part of base href. Now Using test box I want to override the value.

For Client1: So the initial URL is https://example.com/portalId/Login ". When I enter any number in the text box the URL should change to Ex: https://example.com/21/Login Portal and JWT token I am storing in session storage. After Successful login, every routing must have the portalID. Something like this https://example.com/21/home

For Client2: In New window (Now PortalId is 45) The URL is https://example.com/45/Login Here also portalID and JWT token is saved in session storage. After Successful login, every routing must have the portalID. Something like this https://example.com/45/home

This will have to be acomplished using routing. Follow this tutorial: https://www.learnhowtoprogram.com/javascript/angular-extended/dynamic-routing-navigation . You will have to set in your code the route you want to navigate to. Example: this.router.navigate([**DyanamicPortalID**, 'Login']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM