Class has or is using name 'SafeUrl' from

2019-09-17 14:15发布

问题:

I'm using sanitizer.bypassSecurityTrustUrl to put links to blobURL's on the page. This works just fine as long as I don't AoT compile the project.

import {DomSanitizer} from '@angular/platform-browser';

export class AppComponent {
  constructor(private sanitizer: DomSanitizer) {
  }

  sanitize(url: string) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }
}

The sanitize function takes a URL like this:

blob:http://localhost:4200/7c1d7221-aa0e-4d98-803d-b9be6400865b

If I use AoT compilation I get this error message:

Module build failed: Error: /.../src/app/app.component.ts (18,3): Return type of public method from exported class has or is using name 'SafeUrl' from external module "/.../node_modules/@angular/platform-browser/src/security/dom_sanitization_service" but cannot be named.)

I'm using CLI with Angular 2.1.0

Anybody knows how I can circumvent this problem? Or should it be reported as a bug?

回答1:

So it seems I had to add a return type of SafeUrl to the method

  sanitize(url: string):SafeUrl {
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }

Big thanks to alxhub



回答2:

In my case i was initiating an attribute like this :

public img64 = this.domSanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,' + this.base64Image);

Resulting in the same error.

Thanks to @mottosson I got it right (just add the type SafeUrl):

public img64: SafeUrl = this.domSanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,' + this.base64Image);