Javascript 使用 Angular 2 RC6 为组件提供 DomSanitizer 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39438039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way Provide DomSanitizer to Component with Angular 2 RC6
提问by kalmas
I'm attempting to use DomSanitizer to sanitize a dynamic URL within a Component using I can't seem to figure out what the correct way to specify a Provider for this service is.
我正在尝试使用 DomSanitizer 清理组件内的动态 URL,我似乎无法弄清楚为此服务指定提供者的正确方法是什么。
I'm using Angular 2.0.0-rc.6
我正在使用Angular 2.0.0-rc.6
Here's my current component:
这是我当前的组件:
@Component({
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [ DomSanitizer ],
})
export class AppComponent implements OnInit
{
public url: SafeResourceUrl;
constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {
let id = 'an-id-goes-here';
let url = `https://www.youtube.com/embed/${id}`;
this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
ngOnDestroy() {}
}
This results in the error this.sanitizer.bypassSecurityTrustResourceUrl is not a function
at runtime.
这会导致this.sanitizer.bypassSecurityTrustResourceUrl is not a function
运行时出错。
Could someone show me an example of how to properly provide a Provider for DomSanitizer? Thanks!
有人可以向我展示如何正确提供 DomSanitizer 提供程序的示例吗?谢谢!
回答by micronyks
You don't need to declare providers: [ DomSanitizer ]
anymore.
Just need to import
DomSanitizer
as shown below,
你不需要再声明providers: [ DomSanitizer ]
了。
只需要如下图,import
DomSanitizer
import { DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';
in component inject it through a constructor as below,
在组件中通过构造函数注入它,如下所示,
constructor(private sanitizer: DomSanitizer) {}
回答by Sanket
Import these-
导入这些-
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
define variable-
定义变量-
trustedDashboardUrl : SafeUrl;
Use it in constructor like this-
在这样的构造函数中使用它 -
constructor(
private sanitizer: DomSanitizer) {}
Specifiy URL like this-
像这样指定 URL-
this.trustedDashboardUrl =
this.sanitizer.bypassSecurityTrustResourceUrl
("URL");
See if this helps.
看看这是否有帮助。
回答by Günter Z?chbauer
Both should work
两者都应该工作
constructor(private sanitizer: DomSanitizer) {}
constructor(private sanitizer: Sanitizer) {}
Injecting DomSanitizer
is better because only this type provides the necessary methods without casting.
注入DomSanitizer
更好,因为只有这种类型提供了不需要铸造的必要方法。
Ensure you have imported the BrowserModule
确保您已导入 BrowserModule
@NgModule({
imports: [BrowserModule],
})
See also In RC.1 some styles can't be added using binding syntax