question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Provider APP_BASE_HREF does not work with useFactory

See original GitHub issue

Which @angular/* package(s) are the source of the bug?

common

Is this a regression?

No

Description

Currently, the APP_BASE_HREF provider only seems to work with useValue. Hence, if you need to obtain this value dynamically, you can’t. The internals of the PathLocationStrategy doesn’t understand the Promise<string> from the useFactory.

Please provide a link to a minimal reproduction of the bug

https://stackblitz.com/edit/angular-ivy-vznsgo?file=src/app/app.module.ts

Please provide the exception or error you saw

main.ts:13 TypeError: url.replace is not a function
    at _stripIndexHtml (common.js:796:1)
    at new Location (common.js:591:1)
    at Object.Location_Factory [as factory] (common.js:747:48)
    at R3Injector.hydrate (core.js:11457:1)
    at R3Injector.get (core.js:11276:1)
    at injectInjectorOnly (core.js:4770:1)
    at ɵɵinject (core.js:4774:1)
    at injectArgs (core.js:4851:1)
    at Object.factory (core.js:11541:1)
    at R3Injector.hydrate (core.js:11457:1)
(anonymous) @ main.ts:13
invoke @ zone.js:372
run @ zone.js:134
(anonymous) @ zone.js:1275
invokeTask @ zone.js:406
runTask @ zone.js:178
drainMicroTaskQueue @ zone.js:585
Promise.then (async)
nativeScheduleMicroTask @ zone.js:561
scheduleMicroTask @ zone.js:572
scheduleTask @ zone.js:396
scheduleTask @ zone.js:221
scheduleMicroTask @ zone.js:241
scheduleResolveOrReject @ zone.js:1265
then @ zone.js:1450
bootstrapModule @ core.js:29345
73067 @ main.ts:12
__webpack_require__ @ bootstrap:19
__webpack_exec__ @ lib|semver:1
(anonymous) @ lib|semver:1
__webpack_require__.O @ chunk loaded:23
(anonymous) @ lib|semver:1
webpackJsonpCallback @ jsonp chunk loading:33
(anonymous) @ main.js:1


### Please provide the environment you discovered this bug in (run `ng version`)

```true
Angular CLI: 12.2.13
Node: 14.18.1
Package Manager: yarn 1.22.18
OS: darwin x64

Angular: 12.2.13
... animations, cli, common, compiler, compiler-cli, core
... elements, forms, language-service, platform-browser
... platform-browser-dynamic, platform-server, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1202.0
@angular-devkit/build-angular   12.2.13
@angular-devkit/core            12.2.13
@angular-devkit/schematics      12.2.13
@angular/cdk                    12.2.12
@nguniversal/builders           12.1.3
@nguniversal/common             12.1.3
@nguniversal/express-engine     12.1.3
@schematics/angular             12.2.13
ng-packagr                      12.2.5
rxjs                            6.5.5
typescript                      4.3.5
webpack                         5.70.0

Anything else?

This was happening on v11, it didn’t change on v12 and still happening on v13. It seems like this line needs to handle the promise properly or maybe somewhere else before this as the location seems to expect string for the _baseHref all the way through.

NOTE: On stackblitz, even if I remove the <base href="/"> from the index.html, it shows up in there. On our app, this is not defined (on purpose) and it’s the reason it throws the exception above.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
fbaba-nibtravelcommented, May 22, 2022

That’s great @Totati !! Thanks for your detailed reply! That helped a lot! Cheers

1reaction
Totaticommented, May 20, 2022

Once we used an InjectionToken for storing app config.

import { InjectionToken } from '@angular/core';

// The interface with all the props that can be configured;
export interface Config {
  baseHref: string;
}

// InjectionToken for storing the values
export const CONFIG = new InjectionToken<Config>('CONFIG', {
  // Return an empty object that will hold the values;
  factory: () => ({} as Config),
});

export function getConfig(config: Config) {
  return () => {
    return fetch('https://run.mocky.io/v3/976c500a-d87c-4dc6-b475-130a2ef41f67')
      .then((resp) => resp.json())
      .then((body) => {
        // assign all the values returned to the config object
        // we did freeze it so noone can change it later
        Object.freeze(Object.assign(config, body));
      });
  };
}

This token can be injected anywhere

[
  {
    provide: APP_INITIALIZER,
    useFactory: getConfig,
    multi: true,
    deps: [CONFIG],
  },
  {
    provide: APP_BASE_HREF,
    useFactory: (config: Config) => config.baseHref,
    deps: [CONFIG],
  },
]
Read more comments on GitHub >

github_iconTop Results From Across the Web

angular - using injectable service to set configuration of ...
now I want to use that injectable service on my app-module.ts in order to set the APP_BASE_HREF provider. import { BrowserModule } from...
Read more >
Using Angular's Base HREF in Paths - Shawn Wildermuth
The problem is that the Angular app just renders HTML for the browser to ... providers: [ { provide: APP_BASE_HREF, useFactory: getBaseHref, ...
Read more >
Angular — use APP_BASE_HREF to dynamically calculate ...
Angular — use APP_BASE_HREF to dynamically calculate case-insenstive baseHref. Use case. Let's say you are building an app with multiple ...
Read more >
Angular: Set Base URL Dynamically - Project Codify
If we want to change the base URL, we have two problems to solve: ... Register a base URL provider in the module...
Read more >
Service provider: useFactory | Angular Tutorial - YouTube
Your browser can't play this video. Learn more. Switch camera ... Service provider : useFactory | Angular Tutorial. 552 views 3 months ago....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found