Angular2如何以编程方式获取APP_BASE_HREF?

2024-01-25

如何以编程方式获取 APP_BASE_HREF?

我的 app.module.ts 中有这个(其中 APP_BASE='/'):

{
    provide: APP_BASE_HREF,
    useValue: '<%= APP_BASE %>'
},

我想:

import { APP_BASE_HREF } from '@angular/common'; 
...
console.debug(APP_BASE_HREF.toString());

在控制台中我得到:

Token appBaseHref

我需要得到:

http://localhost:5555/

感谢这些答案@Günter Zöchbauer https://stackoverflow.com/users/217408/g%C3%BCnter-z%C3%B6chbauer:

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

...我拼凑了这样的方法:


索引.html

<!DOCTYPE html>
<html lang="en-us">
<head>
    <base href="/" />
    <meta charset="utf-8" />
    <title>Testing APP_BASE_HREF</title>
    <link rel="icon" type="image/png" href="favicon.ico" sizes="16x16" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
        <app-root></app-root>
</body>
</html>

应用程序模块.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 `<base href="" />` 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 `<base href="" />` 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 { }

应用程序组件.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 {
    }
}

应用程序.组件.规格.ts

import { TestBed, ComponentFixture, async } from "@angular/core/testing";
import { APP_BASE_HREF } from "@angular/common";

describe("AppComponent", () => {

    let component: AppComponent,
        fixture: ComponentFixture<AppComponent>;

    // 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();
    }));
});

然后你可以做这样的事情:

  1. npm start

APP_BASE_HREF 将等于 index.html 中设置的默认值

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

APP_BASE_HREF 将等于传递给 base-href 标志的值

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2如何以编程方式获取APP_BASE_HREF? 的相关文章

随机推荐