简体   繁体   中英

Dynamic base-href for Angular

I have a request from a customer to run an Angular App with a subpath like "www.domain.com:9083/portal". Problem is that the angular app does not know about the subpath when it is loaded. The only hint is the url from browser. Server is a C# Nancyfx application.

I've tried to detect dynamically the base-ref with a script

<script>
    // manually sets the <base> tag's href attribute so the app can be located in places other than root
    var split = location.pathname.split('/');
    var base = "";
    if (split.length > 1 && split[1] != "") {
      base += "/" + split[1] + "/";
    }
    window['_app_base'] = base;
    document.write("<base href='" + base + "' />");

  </script>

But this resulted in more problems.

Is there an chance to create a base-ref depending on the called sub-path. So base-ref for "www.domain.com:9083/portal" would be "/portal", if server is configured to run on "www.domain.com:9083/newapp" it would be "/newapp".

Is that even possible? Next problem I have a REST API and to update all routes dynamically (like /api/user/getusers to portal/api/user/getusers) I need to access the base-href. Is it stored somewhere or accessible in Angular?

Thanks for help Regards

Use APP_BASE_HREF token to set base url dyanmically.

app.module.ts

import { NgModule,Inject } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';
import { APP_BASE_HREF } from '@angular/common';

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule.forRoot([]) ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: [
    {
      provide: APP_BASE_HREF,
      useFactory:()=>{
          return window.location.host === "www.domain.com:9083/portal" ? '/portal' : '/newapp';
      } 
    }
  ]
})
export class AppModule { 
}

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