Search code examples
javascriptangularwebangular-providers

Angular UrlResolver is not overridden by custom provider


I have an Angular application in which I'd like to use a custom UrlResolver provider in order to add some cache breaking logic, as seen in this question (https://stackoverflow.com/a/43289767/868914).

However it doesn't seem that I can override the default compiler UrlResolver using a provider, as I would normally do and as the above link suggests.

Here is a plunker showing what I mean: https://plnkr.co/edit/zFsdyfNIoPcmbLO7WafW?p=preview

If you use the chrome (or other good) dev tools debugger to view the source for compiler.umd.js and search for the UrlResolver and put a break in the 'resolve' method, you can see the default implementation is being used instead of my provided class.

I cannot find a reason for this, hopefully someone on here knows a reason / solution?

Heres app.module code (as seen on the plunkr also)

//our root app component
import {Component, NgModule, VERSION} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { UrlResolver } from "@angular/compiler";

@Component({
  selector: 'my-app',
  templateUrl: 'my-app.html',
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

class NewUrlResolver extends UrlResolver {

    resolve(baseUrl: string, url: string): string {
       console.log("Custom resolve");
       return "rubbish";
    }
}

@NgModule({
  imports: [ BrowserModule ],
  providers: [{
    provide: UrlResolver, useClass: NewUrlResolver
  }]
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Solution

  • You should provide your custom UrlResolver as part of providers in CompilerOptions when bootstraping application:

    platformBrowserDynamic().bootstrapModule(AppModule, { 
      providers: [{ provide: UrlResolver, useClass: NewUrlResolver 
    }]})
    

    Plunker Example