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

sur*_*sea 10 angular

如何以编程方式获取APP_BASE_HREF?

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

{
    provide: APP_BASE_HREF,
    useValue: '<%= APP_BASE %>'
},
Run Code Online (Sandbox Code Playgroud)

我尝试着:

import { APP_BASE_HREF } from '@angular/common'; 
...
console.debug(APP_BASE_HREF.toString());
Run Code Online (Sandbox Code Playgroud)

在控制台我得到:

Token appBaseHref
Run Code Online (Sandbox Code Playgroud)

我需要得到:

http://localhost:5555/
Run Code Online (Sandbox Code Playgroud)

Ian*_*ell 18

感谢@GünterZöchbauer的这些答案:

......我拼凑了这样一种方法:


的index.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>
Run Code Online (Sandbox Code Playgroud)

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 `<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 { }
Run Code Online (Sandbox Code Playgroud)

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 {
    }
}
Run Code Online (Sandbox Code Playgroud)

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<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();
    }));
});
Run Code Online (Sandbox Code Playgroud)

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

  1. npm start

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

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

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

  • 请注意,如果您只想获取基本 href 值,那么现在有更简单的方法。请参阅此[SO答案](/sf/answers/4249404001/)。 (3认同)
  • 谢谢!!这解决了我的问题。这是一个 PITA,必须注入 BaseRef 并将其绑定到所有 src 或 href 引用,但至少它确实有效。不明白为什么这个问题还没有得到解决。 (2认同)

Gün*_*uer 13

只需将其注入服务或组件即可

import { APP_BASE_HREF } from '@angular/common'; 

...

constructor(@Inject(APP_BASE_HREF) private baseHref:string) {
  console.log(this.baseHref);
}
Run Code Online (Sandbox Code Playgroud)

  • 它对我不起作用.我有这样的错误消息:`没有提供令牌appBaseHref` (4认同)
  • 仅供参考:收到此错误:`"没有提供者注入FeedToken appBaseHref" (3认同)
  • 您需要自己提供 `providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]`。默认为`/`。 (2认同)

mat*_*ani 5

如果使用 PathLocationStrategy,Angular 现在有LocationStrategy.getBaseHref()( https://angular.io/api/common/LocationStrategy )。

例如,在app.module.ts:

...
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
...
@NgModule({
  providers: [
    ...
    {provide: LocationStrategy, useClass: PathLocationStrategy},
    ...
  ],
  ...
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

然后在您的服务/组件/...:

constructor(private locationStrategy: LocationStrategy, ...) {
  console.log(this.locationStrategy.getBaseHref());
  ...
}
Run Code Online (Sandbox Code Playgroud)