Angular2 How to get APP_BASE_HREF programmatically?

后端 未结 3 762
傲寒
傲寒 2020-12-31 10:33

How to get APP_BASE_HREF programmatically?

I have this in my app.module.ts (where APP_BASE=\'/\'):

{
    provide: APP_BASE_HREF,
    useValue: \'<         


        
3条回答
  •  再見小時候
    2020-12-31 11:03

    Thanks to these answers by @Günter Zöchbauer:

    • https://stackoverflow.com/a/39287458/1298685
    • https://stackoverflow.com/a/38485296/1298685

    ...I have pieced together an approach like this:


    index.html

    
    
    
        
        
        Testing APP_BASE_HREF
        
        
    
    
            
    
    
    

    app.module.ts

    import { APP_BASE_HREF, PlatformLocation } from "@angular/common";
    import { AppComponent } from "./app.component";
    
    /**
     * This function is used internal to get a string instance of the `` value from `index.html`.
     * This is an exported function, instead of a private function or inline lambda, to prevent this error:
     *
     * `Error encountered resolving symbol values statically.`
     * `Function calls are not supported.`
     * `Consider replacing the function or lambda with a reference to an exported function.`
     *
     * @param platformLocation an Angular service used to interact with a browser's URL
     * @return a string instance of the `` value from `index.html`
     */
    export function getBaseHref(platformLocation: PlatformLocation): string {
        return platformLocation.getBaseHrefFromDOM();
    }
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        providers: [
            {
                provide: APP_BASE_HREF,
                useFactory: getBaseHref,
                deps: [PlatformLocation]
            }
        ],
        bootstrap: [
            AppComponent
        ]
    })
    export class AppModule { }
    

    app.component.ts

    import { Component, OnInit, Inject } from "@angular/core";
    import { APP_BASE_HREF } from "@angular/common";
    
    @Component({
        selector: "app-root",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.scss"]
    })
    export class AppComponent implements OnInit {
    
        constructor(@Inject(APP_BASE_HREF) private baseHref: string) {
            console.log(`APP_BASE_HREF is ${this.baseHref}`);
        }
    
        ngOnInit(): void {
        }
    }
    

    app.component.spec.ts

    import { TestBed, ComponentFixture, async } from "@angular/core/testing";
    import { APP_BASE_HREF } from "@angular/common";
    
    describe("AppComponent", () => {
    
        let component: AppComponent,
            fixture: ComponentFixture;
    
        // configuring dependencies
        beforeEach(async(() => {
            TestBed.configureTestingModule({
                declarations: [
                    AppComponent
                ],
                providers: [
                    {
                        provide: APP_BASE_HREF,
                        useValue: "/"
                    }
                ]
            }).compileComponents();
        }));
    
        // getting component
        beforeEach(() => {
            fixture = TestBed.createComponent(AppComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
        });
    
        // tests
        it("should create the app", async(() => {
            const app: any = fixture.debugElement.componentInstance;
            expect(app).toBeTruthy();
        }));
    });
    

    Then you could do stuff like this:

    1. npm start

    APP_BASE_HREF will equal the default value set in index.html

    1. npm run build --base-href /foobar/

    APP_BASE_HREF will equal the value passed to the base-href flag

提交回复
热议问题